我正在尝试制作一个计数器,但由于某种原因我的代码无法工作,我真的不知道还能做什么。 如果我点击值为 1 的按钮,H1 应该自动更改。
当我检查页面时,我看到了您在屏幕截图中看到的错误
我的代码中有什么我看不到的错误吗?
<div id="app"></div>
<script type="text/babel">
var CounterChallenge = React.createClass({
getInitialState: function(){
return{
count: 0
}
},
incrementCount: function(value){
this.setState({
count: this.state.count + value
})
},
getDefaultProps: function(){
return{
valueOne: 1,
valueTwo: 5,
valueThree: 10
}
},
render: function() {
return(
<div>
<h1>Count: {this.state.count}</h1>
<Button value={this.props.valueOne} clickHandler={this.incrementCount.bind(this, this.props.valueOne)}>Add {props.valueOne}</Button>
<Button value={this.props.valueTwo} clickHandler={this.incrementCount.bind(this, this.props.valueTwo)}>Add {props.valueTwo}</Button>
<Button value={this.props.valueThree} clickHandler={this.incrementCount.bind(this, this.props.valueThree)}>Add {props.valueThree}</Button>
</div>
)
}
});
var Button = function(props){
return(
<button value={props.value} onClick={this.clickHandler}> Add {props.value}</button>
)
};
ReactDOM.render(
<CounterChallenge />,
document.getElementById('app')
);
最佳答案
从您发布的错误来看,问题似乎出在每个 Button
组件的内容上:
Add {props.valueOne}
这里的 props
未定义。我认为你的意思是 this.props.valueOne
。
此外,您还可以在按钮中输入两次内容。到达这里后:
<Button value={this.props.valueOne}>Add {props.valueOne}</Button>
然后在实际组件中再次:
var Button = function(props){
return(
<button value={props.value} onClick={this.clickHandler}> Add {props.value}</button>
)
};
编辑:您还需要将按钮的 onClick
更改为 {this.props.clickHandler}
而不是 {this.clickHandler}。 clickHandler}
,因为后者未定义:
return(
<button value={props.value} onClick={this.props.clickHandler}> Add {props.value}</button>
)
关于javascript - react 组件不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373213/