2015-12-02 30 views
5

Tôi đang gặp một số vấn đề với ràng buộc giá trị của đầu vào, tôi đã thực hiện nó trên một thành phần khác của ứng dụng và nó hoạt động tốt, nhưng bằng cách nào đó tôi không thể làm cho nó hoạt động trên một thành phần khác. Tôi chỉ nhận được lá thư đầu tiên và không phải là toàn bộ văn bảnReact, Binding input values ​​

Đây là thành phần của tôi

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

Tôi cũng cố gắng sử dụng một ví dụ từ trang web Phản ứng nhưng nó đã nhận được kết quả tương tự:

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

Có ai có ý tưởng không, tại sao điều này xảy ra?

Trả lời

13

Bạn phải quấn inputbutton trong phần tử gốc (ví dụ div)., Thành phần chỉ có thể có một phần tử gốc.

Bạn có thể sử dụng .bind như trong ví dụ của tôi, và tránh sử dụng 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

Lưu ý: Từ Phản ứng 16. * có Fragments, cho phép bỏ qua phần tử gốc bổ sung.

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

tất nhiên !! nó hoạt động rất đẹp! Cảm ơn bạn đời !! –