【问题标题】:Child Component is not able to trigger state change子组件无法触发状态更改
【发布时间】:2015-10-30 18:17:20
【问题描述】:

简单的反应状态示例。父组件是 App,它一开始只是显示一个按钮,当单击该按钮时,它应该呈现 AllRecipes(这有效,我能够管理 AllRecipes 的状态)。 AllRecipes 内部是一个按钮,需要触发状态更改然后进一步渲染ingredients(单击此按钮时不执行任何操作,它需要切换成分的状态)。我认为这是一个非常好的关于如何管理状态的小例子,但我错过了一些东西..

var App = React.createClass({

    getInitialState: function(){
        return {showIngredients: false, showRecipes: false};
    },

    toggleRecipes: function(){
        this.setState({showRecipes: !this.state.showRecipes})
    },

    toggleIngredients: function(){
        this.setState({showRecipes: !this.state.showRecipes})
    },

  render: function() {
        var recipes = this.state.showRecipes ? <Recipes/> : null;
        return (
                <div>
                    <h1> Recipe App </h1>
                        <button onClick={this.toggleRecipes}> Show Recipes </button>

                        {recipes}
                </div>
            );
    }
});

var Recipes = React.createClass({
    render: function() {
        var ingredients = this.props.showIngredients ? <Ingredients/> : null;
        return (
                <div>
                    <h1> list of recipes </h1>
                        <ul>
                            <li> Chicken Soup </li>
                            <li> Chicken Wings </li>
                            <button onClick={this.props.toggleIngredients}> Show Recipes </button>
                            {ingredients}
                        </ul>
                </div>

            );
    }
});

var Ingredients = React.createClass({
    render: function() {
        return (
                <div>
                    <h1> List of Ingredients </h1>
                        <ul>
                            <li> Salt </li>
                            <li> Pepper </li>
                        </ul>
                </div>
            );
    }
});

React.render(<App/>, document.body);

【问题讨论】:

  • 基本上食谱组件根本看不到父组件app中的toggleIngredients函数。是我错误地设计了流程,还是遗漏了一些小东西?

标签: javascript reactjs state


【解决方案1】:

您似乎没有将toggleIngredients 传递给Recipes。尝试改变

var recipes = this.state.showRecipes ? <Recipes/> : null;

var recipes = this.state.showRecipes ? <Recipes toggleIngredients={this.toggleIngredients} /> : null;

【讨论】:

  • 是的,我认为这绝对是我出错的地方!我收到此错误Uncaught Error: Invariant Violation: Expected onClick listener to be a function, instead got type string 您的帖子是否有语法错误?
  • 应该是这样的吗? &lt;Recipes toggleIngredients="{this.toggleIngredients}" /&gt;
  • 是的,看起来不错(与我发布的内容类似,但使用了正确的方法名称 - 抱歉;)。
  • 啊,不应该被引用...更新答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 2020-09-20
相关资源
最近更新 更多