2015-12-02 12 views
5

Ich habe einige Probleme mit dem Wert einer Eingabe zu binden, ich habe es auf einer anderen Komponente meiner App getan und es hat gut funktioniert, aber irgendwie kann ich nicht funktioniert es auf einer anderen Komponente. Ich bin nur den ersten Buchstaben bekommen und nicht den ganzen TextReact, Binding Eingabewerte

Dies ist meine Komponente

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}); 
} 
} 

Ich versuchte auch von ein Beispiel zu verwenden Website reagieren, aber es hat das gleiche Ergebnis:

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}); 
    } 
    } 

Hat jemand eine Idee, warum das passiert?

Antwort

13

Sie müssen input und button in Wurzel Element wickeln (zB div). Kann die Komponente nur ein Wurzelelement haben.

Sie können .bind wie in meinem Beispiel verwenden, und vermeiden 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

Hinweis verwendet: Von 16. Reagieren * dort Fragments ist, das Wurzelelement Überspringen zusätzliche ermöglicht.

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

natürlich !! es hat schön funktioniert! Danke Kumpel !! –