2016-10-16 48 views
0

我想映射出一個對象到可以更新onChange的輸入。除了組件在this.setState()之後永遠不會更新之外,所有組件都可以工作從對象更新onChange映射的輸入React.JS

var ItemModal = React.createClass({ 
    getInitialState: function(){ 
    return { 
     title: "", 
     cooktime: "", 
     ingredients: [], 
     instructions: "" 
    } 
    }, 

    componentWillReceiveProps: function(nextProps) { 
    this.setState({ 
     title: nextProps.inputVal.title, 
     cooktime: nextProps.inputVal.cooktime, 
     ingredients: nextProps.inputVal.ingredients, 
     instructions: nextProps.inputVal.instructions 
    }); 
}, 

    handleChange: function(event){ 
    var change = {}; 
    console.log(event.target.id + " " + event.target.value) 
    change[event.target.id] = event.target.value; 
    console.log(change); 
    this.setState(change); 
}, 

    render: function(){ 
    var handleChange = this.handleChange; 
    var inputVal = this.props.inputVal; 
    return (
     <div id="itemModal"> 
     <div id="modalContent"> 
      { 
      Object.keys(this.props.inputVal).map(function(curr){ 
       return <input id={curr} placeholder= "Recipe Name Here!" type="text" value= {inputVal[curr]|| ""} onChange = {handleChange.bind(this)}/> 
     }) 
     } 
     </div> 
     </div> 
    ); 
    } 
}); 

link to code

轉到ItemModal代碼我提的是在那裏。

回答

0

handleChange是在一個類中。所以,你需要使用this來在課堂上訪問它。如下更改您的render

render: function(){ 
    var handleChange = this.handleChange; 
    var inputVal = this.props.inputVal; 
    var _this = this; 
    return (
     <div id="itemModal"> 
     <div id="modalContent"> 
      { 
      Object.keys(this.props.inputVal).map(function(curr){ 
       return <input id={curr} placeholder= "Recipe Name Here!" type="text" value= {inputVal[curr]|| ""} onChange = {_this.handleChange.bind(_this)}/> 
     }) 
     } 
     </div> 
     </div> 
    ); 
    }