我有一个调用setmenu函数的点击(在className ="菜单"列表中),但我不想在我的3个不同的回复中重复它。相反,我想将它放入自己的函数/组件中并调用它3次。
然而,当我移动它时,点击不能找到setmenu,即使我仍然有this.setmenu = this.setmenu.bind(this);在构造函数中?
setmenu(event, value){
this.setState({showForm: value});
console.log(this.state.showForm, "this.state.showForm")
}
render() {
const showForm = this.state.showForm;
if (showForm === 1){
return (
<div>
<ul className="menu">
<li><a href="javascript:void(0)" onClick={e => this.setmenu(e, 1)}>Form 1</a></li>
<li><a href="javascript:void(0)" onClick={e => this.setmenu(e, 2)}>Form 2</a></li>
<li><a href="javascript:void(0)" onClick={e => this.setmenu(e, 3)}>Form 3</a></li>
</ul>
<FacebookLoginForm value={this.state.facebookResponse} />
</div>
);
}
else if(showForm === 2) {
return (
<div>
<ul className="menu">
<li><a href="javascript:void(0)" onClick={e => this.setmenu(e, 1)}>Form 1</a></li>
<li><a href="javascript:void(0)" onClick={e => this.setmenu(e, 2)}>Form 2</a></li>
<li><a href="javascript:void(0)" onClick={e => this.setmenu(e, 3)}>Form 3</a></li>
</ul>
<ManualLoginForm />
</div>
);
}
else if (showForm === 3){
return (
<div>
<ul className="menu">
<li><a href="javascript:void(0)" onClick={e => this.setmenu(e, 1)}>Form 1</a></li>
<li><a href="javascript:void(0)" onClick={e => this.setmenu(e, 2)}>Form 2</a></li>
<li><a href="javascript:void(0)" onClick={e => this.setmenu(e, 3)}>Form 3</a></li>
</ul>
<ManualRegForm />
</div>
)
}
}
答案 0 :(得分:1)
href
属性读取其他参数,而不是使用其他参数调用处理程序href="javascript:void(0)"
来阻止
function Links(props) {
return (
<div>
<ul className="menu">
{props.children.map((e, key) => <li key={key} onClick={props.clickHandler}>{e}</li>)}
</ul>
</div>
);
}
class App extends React.Component {
constructor() {
super()
this.setmenu = this.setmenu.bind(this);
}
setmenu(event, value){
event.preventDefault();
console.log('setmenu: ', event.target.getAttribute('href'))
}
render() {
return (
<Links clickHandler={this.setmenu}>
<a href="3">Form 3</a>
<a href="2">Form 2</a>
</Links>
);
}
}
ReactDOM.render(<App/>,
document.querySelector('#app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">Loading...</div>
&#13;
答案 1 :(得分:0)
工作示例:https://jsfiddle.net/wostex/4wcdL6dw/3/
将你的职能作为道具传递。
function ThreeLinks(props) {
return (
<div>
<ul className="menu">
<li><a href="javascript:void(0)" onClick={(e) => props.clickHandler(e, 1)}>Form 1</a></li>
<li><a href="javascript:void(0)" onClick={(e) => props.clickHandler(e, 2)}>Form 2</a></li>
<li><a href="javascript:void(0)" onClick={(e) => props.clickHandler(e, 3)}>Form 3</a></li>
</ul>
</div>
);
}
class App extends React.Component {
setmenu(event, value){
console.log('setmenu: ', event, value)
}
render() {
return (
<ThreeLinks clickHandler={this.setmenu.bind(this)} />
);
}
}