2015-12-02 56 views
5

我在綁定輸入值時遇到了一些問題,我在應用程序的另一個組件上完成了它,但它工作正常,但不知何故我無法讓它在另一個組件上工作。我只獲得第一個字母,而不是整個文本反應,綁定輸入值

這是我的組件

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

我還試圖用從網站做出反應的例子,但它得到了相同的結果:

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

有人有想法,爲什麼發生這種情況?

回答

13

您必須將inputbutton包含在元素(例如div)中,組件只能有一個根元素。

你可以在我的例子中使用.bind等,避免使用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

注:從陣營16 *有Fragments,它允許跳過額外的根元素。

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

當然!!它工作很美麗!謝了哥們!! –