我开始使用 React,但我一直坚持这个示例。
计数器可以工作,但为什么 onClick 按钮不会更改处于事件状态的按键并呈现正确的按钮?
链接到CodePen
const Button = ({label}) => (
<button className="btn btn-primary">{label}</button>
);
const Counter = React.createClass({
getInitialState: function () {
return {
counter: 0,
active: false
}
},
increment: function () {
this.setState({
counter: this.state.counter + 1
})
},
change: function () {
this.setState({
active: true
})
},
render: function () {
return (
<div>
<h1>Counter: {this.state.counter}</h1>
<button onClick={this.increment}>1+</button>}
{this.state.active ?
<Button label="Sign OUT"/> :
<Button label="Sign in" onClick={this.change}/>}
</div>
)
}
});
ReactDOM.render(<Counter/>, document.getElementById("root"))
最佳答案
因为您忘记在 Button
组件中定义 click
事件,请使用此:
const Button = (props) => (
<button className="btn btn-primary" onClick={props.onClick}>{props.label}</button>
);
还有一件事,您还需要使用 signout
按钮定义点击事件,如下所示:
{this.state.active ?
<Button label="Sign OUT" onClick={this.change}/> :
<Button label="Sign in" onClick={this.change}/>
}
change: function () {
this.setState({
active: !this.state.active
})
}
检查工作示例:
jsfiddle
:https://jsfiddle.net/mtbg3g59/
关于javascript - ReactJS中的通用按钮组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42200084/