我正在学习React,并且在向点击功能发送道具时遇到问题。我正在尝试创建一个简单的ES6计数器组件,该组件在单击按钮时会递增。
我的点击功能很简单:
click() {
this.setState({
count: this.state.count + value
})
}
我已经设置了defaultProps:
Counter.defaultProps = { valueOne: 1 }
并在渲染功能中创建了我的按钮:
<Button className="btn" clickHandler={this.click} text="Click me" value={this.props.valueOne}/>
但是我无法弄清楚谁可以通过点击这个按钮来“发送”点击功能。我刚收到消息value is not defined
。
有人能指出我在正确的方向吗?
感谢任何帮助。
我的完整代码是:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.click = this.click.bind(this);
}
click() {
this.setState({
count: this.state.count + value
})
}
render() {
return (
<div className="container">
<h1>Count {this.state.count}</h1>
<Button className="btn blue-btn" clickHandler={this.click} text="Click me" value={this.props.valueOne}/>
</div>
)
}
}
Counter.defaultProps = { valueOne: 1 } //Defaults
const Button = (props) => {
return (
<button className={props.className} onClick={props.clickHandler} value={props.value}>{props.text}</button>
)
}
ReactDOM.render(
<Counter valueOne={1} valueTwo={10} valueThree={100} />,
document.getElementById('app')
);
答案 0 :(得分:3)
它位于event.target.value
,只需将处理程序更改为:
click(event) {
this.setState({
count: this.state.count + event.target.value
})
}
答案 1 :(得分:1)
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0,
valueOne: 1
};
this.click = this.click.bind(this);
}
click(event) {
this.setState({
count: this.state.count + event.target.value
})
}
render() {
return (
<div className="container">
<h1>Count {this.state.count}</h1>
<Button className="btn blue-btn" clickHandler={this.click} text="Click me" value={this.state.valueOne}/>
</div>
)
}
}
这实质上是你想要做的吗?
答案 2 :(得分:0)
您可以使用event.target.value
访问该值。
但我注意到您的代码中可能存在错误,因为this.setState
可以异步执行(如here所述)。您最好使用接受回调的第二个版本的setState,而不仅仅是一个对象。像这样:
click(event) {
this.setState((prevState) => {
return {
count: prevState.count + event.target.value
}
})
}