javascript - Passing input state around in react -


i have react class has code:

  getinitialstate: function(){     return {       results: false,       value: ''     };   },    handleclick: function(event) {     this.setstate({ results: true });     event.preventdefault();   },    handlechange: function(event){     this.setstate({value: event.target.value})   },      <input type="text" id="playername" value={this.state.value} onchange={this.handlechange} placeholder="name" /> 

in react class

i have:

myfunc: function() {     this.setstate({info: true})     let name = this.props.value;     console.log(name) --> returns undefined   }, 

how can name equal name user typed in passing down 1 react class another

i can post more code thought props way pass down code needed elsewhere. this.state.value returns undefined

edit:

myfunc called here:

<input type="submit" value="i can play" onclick={() => this.myfunc()}/> 

the easiest way work have container component, container component handle state management , wrap around child components:

<wrappercomponent>  <input/>  <info /> </wrappercomponent 

your input can still have own state if want debouncing , things wrapper component have own functions set own state , passes functions down input input can call them new values , wrapper component update , info component receive value props wrapper component , in sync.

here example codepen http://codepen.io/finalfreq/pen/vkpxon

class wrapper extends react.component {       constructor() {   super();     this.state = {       value: 'default'     }   }    _handlechange = (value) => {     this.setstate({value: value})     };    render() {     return (       <div>        <input onchange={this._handlechange} value={this.state.value}/>        <info value={this.state.value} />       </div>     )   } }  class input extends react.component {   constructor(props) {     super(props);      this.state = {       value: props.value     }   }    onchange = (e) => {     this.setstate({value: e.target.value});     this.props.onchange(e.target.value);   };    render() {     return <input type="text" value={this.state.value} onchange={this.onchange} />   } }  const info = (props) => {   return (    <h1> {props.value} </h1>   ) }   reactdom.render(<wrapper />,document.getelementbyid('app')); 

obviously can convert using createclass version doesn't have using es6 version. main take away here if want share values across components aren't directly related going want state container component handling everything.

here great article going on container vs presentational components https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -