在React JS中将道具传递给父级

时间:2015-04-01 08:36:37

标签: javascript reactjs

这里我有一个带有默认编号" 3"的文本字段,我希望在输入值并单击按钮时更新它。因为,我更新了Child中的值,我不知道如何将道具传递给Parent。

var Game = React.createClass({
    getInitialState: function() {
        return {
           input: 3
        };
    },

    setSize: function() {
        //here it should update "input"
        this.setState({input: /* value from Child */ })
    },

    render: function() {
        return( 
            <div>
                <div id='game'>
                    <Menu input={this.state.input}/>
                </div>
            </div>
        )
    }  
});


var Menu = React.createClass({
    render: function() {
        return (
            <div id='menu'>
                <input type="number" id="myNumber" value={this.props.input}> </input>
                <button id="mySetNumber" onclick={this.props.setSize}>Try it</button>
            </div>
        )
    }
})

2 个答案:

答案 0 :(得分:9)

可以是这样的:

var Game = React.createClass({
  changeInput: function(e) {
    this.setState({/* do something */})
 },

 render: function() {
  return (
    <div id="game">
      <Menu onValueChange={this.changeInput} />
    </div>
    )
  }
});

var Menu = React.createClass({
  handleChange: function(e) {
    this.props.onValueChange(/* pass the element or the value */)
  }

 render: function() {
   return (
     <div id="menu">
       <input onChange={this.handleChange}/>
    </div>
   )
  }
})

或多或少这样的事情应该有用。有关详情,请参阅this。我们的想法是将一个回调函数从父级传递给子级。

答案 1 :(得分:3)

var App = React.createClass({
    handleDayGreeting:function(greeting){
        this.setState({dayGreeting:greeting});
    },
    render:function({onClick,message}){     
        return (
            <div>
                <span> Hello ! {message} </span>
                <Greeting handleDayGreeting={this.handleDayGreeting.bind(this)} />              
            </div>          
        );
    }
});

var Greeting = React.createClass({
    sayMorining:function(){
        this.props.handleDayGreeting('Good Morining');
    },
    sayEvening:function(){
        this.props.handleDayGreeting('Hey...! Good Evening');
    },
    render:function(){
        return (
            <div>
                <button onClick={onClick}>Say Morning</button>
                <button onClick={onClick}>Say Evening</button>
            </div>
        );
    }
});