2015-12-02 16 views
5

Ho problemi con il bind del valore di un input, l'ho fatto su un altro componente della mia app e ha funzionato bene, ma in qualche modo non riesco a farlo funzionare su un altro componente. Sto ottenendo soltanto la prima lettera e non l'intero testoReact, Binding input values ​​

Questa è la mia componente

class Post extends Component { 

    constructor(props) { 
    super(props); 
    this.state = { 
     post: this.props.data, 
     comment: '' 
    } 
    Post.context = this; 
    } 
render() { 
<input type="text" value={this.state.comment} onChange={this.handleChange} placeholder="Write a comment..." /> 
     <button className="button comments" onClick={this.handleClick.bind(null,this.state.post.id)}></button> 
} 
handleChange(e) { 
    Post.context.setState({comment: e.target.value}); 
} 
} 

Ho anche cercato di usare un esempio da Reagire sito ma ha ottenuto lo stesso risultato:

render() { 
    var valueLink = { 
     value: this.state.comment, 
     requestChange: this.handleChange 
    }; 
render() { 
    <input type="text" valueLink={valueLink} placeholder="Write a comment..." /> 
      <button className="button comments" onClick={this.handleClick.bind(null,this.state.post.id)}></button> 
    } 
    handleChange(newValue) { 
     Post.context.setState({comment: newValue}); 
    } 
    } 

Qualcuno ha idea, perché questo sta accadendo?

risposta

13

Devi avvolgere input e button in radice elemento (ad esempio div)., Componente può avere un solo elemento radice.

È possibile utilizzare .bind come nel mio esempio, ed evitare di utilizzare Post.context = this;

class Post extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     post: this.props.data, 
     comment: '' 
    }; 
    } 

    render() { 
    return <div> 
     <input 
     type="text" 
     value={this.state.comment} 
     onChange={ this.handleChange.bind(this) } 
     placeholder="Write a comment..." /> 

     <button 
     className="button comments" 
     onClick={ this.handleClick.bind(this, this.state.post.id)}>Button</button> 
    </div> 
    } 

    handleClick(postId, e) { 
    console.log(postId); 
    console.log(this.state.comment); 
    } 

    handleChange(e) { 
    this.setState({ comment: e.target.value }); 
    } 
} 

Example

Nota: Da Reagire 16. * c'è Fragments, che permette di saltare elemento radice supplementare.

render() { 
    return (
    <> 
     <input 
     type="text" 
     value={this.state.comment} 
     onChange={ this.handleChange.bind(this) } 
     placeholder="Write a comment..." 
     /> 

     <button 
     className="button comments" 
     onClick={ this.handleClick.bind(this, this.state.post.id)} 
     > 
     Button< 
     /button> 
    </> 
) 
} 
+1

ovviamente !! ha funzionato bello! Grazie compagno!! –