2017-01-09 120 views
0

我有以下:上改變方法與輸入子陣營控制父狀態

import React from 'react'; 
import {render} from 'react-dom'; 

class TShirt extends React.Component { 
    render() { 
     return <div className="tshirt">{this.props.name}</div>; 
    } 
} 

class FirstName extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      submitted: false 
     }; 
    } 
    getName() { 
     var name = this.refs.firstName.value; 
     this.setState({ submitted: true }, function() { 
      this.props.action(name); 
     }); 
    } 
    render() { 
     return (
      <div> 
       <h2>tell us your first name</h2> 
       <form> 
        <input 
         type="text" 
         ref="firstName" 
         onChange={this.getName.bind(this)} 
        /> 
        <div className="buttons-wrapper"> 
         <a href="#">back</a> 
         <button>continue</button> 
        </div> 
       </form> 
      </div> 
     ); 
    } 
} 

class Nav extends React.Component { 
    render() { 
     return <p>navigation</p>; 
    } 
} 

class App extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      name: '' 
     }; 
    } 
    getName (tshirt) { 
     this.setState({ name:tshirt }) 
    } 
    render() { 
     return (
      <section> 
       <Nav /> 
       <TShirt name={this.state.name} /> 
       <FirstName action={this.getName} /> 
      </section> 
     ); 
    } 
} 

render(<App/>, document.getElementById('app')); 

我特林更新與所述值從所述的onChange方法來(使用的道具)從「T恤」組件「名字「組件。

我有一個整體的狀態包裝內部控制一切,但是當我開始insdie輸入我得到這個錯誤鍵入名稱:

遺漏的類型錯誤:this.setState不是一個函數

指於:

getName (tshirt) { 
    this.setState({ name:tshirt }) 
} 
+1

的[onclick事件中React.js綁定]可能的複製(http://stackoverflow.com/questions/ 27397266/onclick-event-binding-in-react-js) –

回答

1

您必須將getName功能綁定到this

在你的構造函數把

this.getName = this.getName.bind(this); 

那麼你的構造應該看起來像

constructor(props) { 
    super(props); 
    this.state = { 
     name: '' 
    }; 
    this.getName = this.getName.bind(this); 
} 
+0

這是正確的,但您也可以使用ES6胖箭頭函數,它會自動綁定'this',就像'getName(tshirt)=> {...} '。 –