2017-01-09 123 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)=> {...} '。 –