2017-01-01 54 views
0

我在下面的腳本:http://codepen.io/AlexanderWeb00/pen/gLVbjL?editors=0010作出反應得到表單輸入值提交,並顯示它

class Wrapper extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     name: '' 
    }; 
    } 
    handleFirstName(e) { 
    this.setState({name: e.target.value}); 
    } 
    render(){ 
    return (
     <section> 
     <h2>welcome</h2> 
     <TShirt name={this.state.name} /> 
     <FormButton action={this.handleFirstName.bind(this)} /> 
     </section> 
    ) 
    } 
}; 

class TShirt extends React.Component { 
    render(){ 
    return (
     <section> 
     <div> 
      <p>Name: {this.props.name}</p> 
     </div> 
     </section> 
    ) 
    } 
}; 
class Extention extends React.Component { 
    render(){ 
    return (
     <section> 
     <div> 
      <p>badaboom</p> 
     </div> 
     </section> 
    ) 
    } 
}; 
var FormButton = React.createClass({ 
    getInitialState: function() { 
     return {'submitted': false}; 
    }, 

    handleSubmit: function(e) { 
     e.preventDefault(); 
     this.setState({'submitted': true }); 
    }, 
    render: function() { 
     if (this.state.submitted) { 
      return <Extention/>; 
     } 
     else { 
      return (
       <form role="form" onSubmit={this.handleSubmit}> 
        <input type="text" /> 
        <input type="submit" value="submit" /> 
       </form> 
      ); 
     } 
    } 
}); 

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

我想要顯示從輸入

<input type="text" />

這裏收集的值:

<p>Name: {this.props.name}</p>, inside the TShirt component. 

此刻只顯示一個新的c表單提交後的omponent。在構建應用程序時,Tshirt組件將更新更多的內容。

回答

1

您可以使用refs來獲取tshirt輸入字段的值,然後調用傳遞給動作prop中的FormButton組件的回調函數。

var FormButton = React.createClass({ 
getInitialState: function() { 
    return {'submitted': false}; 
}, 

handleSubmit: function(e) { 
    e.preventDefault(); 
    var tshirt = this.refs.tshirt.value; 
    this.setState({submitted: true }, function() { 
     this.props.action(tshirt); 
    }); 
}, 
render: function() { 
    if (this.state.submitted) { 
     return <Extention/>; 
    } 
    else { 
     return (
      <form role="form" onSubmit={this.handleSubmit}> 
       <input type="text" ref="tshirt" /> 
       <input type="submit" value="submit" /> 
      </form> 
     ); 
    } 
} 
}); 

然後修改handleFirstName方法這樣:

handleFirstName(tshirt) { 
    this.setState({name: tshirt}); 
}