javascript - react 组件不工作

标签 javascript reactjs

我正在尝试制作一个计数器,但由于某种原因我的代码无法工作,我真的不知道还能做什么。 如果我点击值为 1 的按钮,H1 应该自动更改。

当我检查页面时,我看到了您在屏幕截图中看到的错误

enter image description here

我的代码中有什么我看不到的错误吗?

<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/

相关文章:

javascript - 有没有办法在handlebars.js中使用toFixed(N)?

javascript - react 路由器 v6 在组件之外导航

reactjs - 使用 react-query 和 react-router-dom 缓存

reactjs - API 请求的 redux 传奇有意义吗?

javascript - 什么是 Microsoft ajax minifier 中的 hypercrunching?

javascript - 你能创建一个只有一页的完整网站吗?

javascript - 如何在reactjs中将值/对象从底部传输到顶部

javascript - 使用 React 进行电子邮件签名

javascript - ES6 动态 Import() 与 AMD require()

reactjs - React 应用程序将在产品刷新页面上给出 404,但在开发中不会