2017-09-06 40 views
0

我想做一個通用輸入的形式,但每次我輸入到我的輸入我失去了這個輸入的重點,我不得不再次點擊它們。反應形式失去了他的重點更新

handleChange(propertyName, event) { 
    const contact = this.state.contact; 
    contact[propertyName] = event.target.value; 
    this.setState({ contact: contact }); 
    } 


render() { 
    const FormInput = (props) => { 
     return (
      <label> 
       Name: 
       <input 
        type="text" 
        placeholder="Enter text" 
        onChange={event => this.handleChange(props.name, event)} 
        value={props.value} 
       /> 
      </label> 
     ) 
    } 

    return (
     <form> 

       <FormInput value={this.state.videoName} name="videoName" /> 
       <FormInput value={this.state.title} name="title" /> 

     </form> 
    ); 
}; 

回答

0

是不是輸入的值需要同步的onchange結果?

考慮這個問題:

handleChange(propertyName, event) { 
    const contact = this.state.contact; 
    contact[propertyName] = event.target.value; 
    this.setState({ contact: contact }); 
} 

constructor(props) { 
    super(); 
    this.state = { 
     contact: props 
    } 
} 

render() { 
    const FormInput = (props) => { 
     return (
      <label> 
       Name: 
       <input 
        type="text" 
        placeholder="Enter text" 
        onChange={event => this.handleChange(props.name, event)} 
        value={this.state.contact.value} 
       /> 
      </label> 
     ) 
    } 

    return (
     <form> 
      <FormInput value={this.state.videoName} name="videoName" /> 
      <FormInput value={this.state.title} name="title" /> 
     </form> 
    ); 
}; 

這個代碼是未經測試,但它相當於getInitialState,你可以做到這一點,或者你可以在handleChange回調添加到您的父組件,更新了它在降下道具

+0

handleChange函數在setState之前的變異狀態是錯誤的,因爲它應該被視爲不可變。 – Nath