2016-07-27 47 views
0

預期:爲什麼不按預期反應組件代碼的功能?

  1. 在改變在輸入框中的文本,標題更新到 消息轉換爲大寫。
  2. 在按下發送按鈕被打印在 控制檯更新消息

結果:

  1. 不工作。控制檯中的錯誤說'this'在函數textBoxChange中是未定義的。 (它在渲染功能,但不是在textBoxChange函數定義?)

Codepen:https://codepen.io/r11na/pen/qNKpQX

class App extends React.Component { 
    textBoxChange(e) { 
    this.props.text = e.target.value; 
    }; 

    sendMessage(e) { 
    console.log("Send message:" + this.props.text); 
    }; 

    render() { 
    return (
     <div> 
     <h3>Your Message: {this.props.text.toUpperCase()}</h3> 
     <MessageBox textBoxChange={this.textBoxChange} sendMessage={this.sendMessage} text={this.props.text}/> 
     </div> 
    ); 
    }; 
}; 

const MessageBox = (props) => { 
    return (
    <div className="row column"> 
     <textarea onChange={props.textBoxChange} value={props.text}></textarea> 
     <button onClick={props.sendMessage} className="button">Send</button> 
     <br/> 
    </div> 
); 
}; 
+2

首先你需要使用'states'而不是'props' - https://codepen.io/anon/pen/XKYEVG。,因爲你不能給'props'分配新的值。 –

+0

感謝亞歷山大是有道理的! – Riina

回答

1

我換成propsstate,加入bind(this)方法和小的變化:

class App extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { text: this.props.text }; 
    } 

    textBoxChange(e) { 
    this.setState({ text: e.target.value }); 
    }; 

    sendMessage(e) { 
    console.log("Send message:" + this.state.text); 
    }; 

    render() { 
    return (
     <div> 
     <h3>Your Message: {this.state.text.toUpperCase()}</h3> 
     <MessageBox 
      textBoxChange={this.textBoxChange.bind(this)} 
      sendMessage={this.sendMessage.bind(this)} 
      text={this.state.text} 
     /> 
     </div> 
    ); 
    }; 
}; 

const MessageBox = (props) => { 
    return (
    <div className="row column"> 
     <textarea onChange={props.textBoxChange.bind(this)} value={props.text}></textarea> 
     <button onClick={props.sendMessage.bind(this)} className="button">Send</button> 
     <br/> 
    </div> 
); 
}; 
相關問題