我想创建几个按钮,每次点击按钮的值都会添加
这就是我得到的
我做了什么冤屈? 什么是"对象" ?
var Button = React.createClass({
localHandleClick: function(){
this.props.localHandleClick(this.props.increment); // get the increment value of each button
},
render: function(){
return(
<button onClick={this.props.localHandleClick }>+{this.props.increment}</button> // this mean use this counter element
)
}
});
var Result = React.createClass({
render: function(){
return(
<div>{this.props.localCounter}</div>
)
}
})
// to include Result => we define Main component
var Main = React.createClass({
getInitialState: function(){
return {counter: 0}; // start from 0
},
// will receive argument
handleClick: function(increment){
this.setState({ counter: this.state.counter+increment }); // read the state and add 1 to value
},
render: function(){
return(
<div>
<Button localHandleClick={this.handleClick} increment={1} />
<Button localHandleClick={this.handleClick} increment={5} />
<Button localHandleClick={this.handleClick} increment={10} />
<Button localHandleClick={this.handleClick} increment={15} />
<Button localHandleClick={this.handleClick} increment={20} />
<Result localCounter={this.state.counter} />
</div>
)
}
})
React.render(<Main />, document.getElementById("root"));
答案 0 :(得分:1)
您需要绑定您的值,而不是设置为属性
<Button localHandleClick={this.handleClick.bind(this, 1)} increment={1}/>
<Button localHandleClick={this.handleClick.bind(this, 5} increment={5}/>
<Button localHandleClick={this.handleClick.bind(this, 10)} increment={10}/>
<Button localHandleClick={this.handleClick.bind(this, 15} increment={15}/>
等等......
这样就传递给了函数。 Button组件的属性未通过。