2015-12-02 8 views
5

Bir girdinin değerini bağlama konusunda bazı sorunlar yaşıyorum, bunu uygulamanızın başka bir bileşeninde yaptım ve iyi çalıştı, ancak bir şekilde başka bir bileşen üzerinde çalışamam. Ben sadece ilk harfi değil, bütün mesaj geldiTepki, Ciltleme giriş değerleri

Bu benim de web sitesi Tepki bir örnek kullanmaya çalıştı

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

benim bileşenidir ama aynı sonucu var:

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

Birisi bir fikri var, neden bu oluyor?

cevap

13

Sen (örneğin div) kök elemanı. Içinde input ve button sarmak gerekir, bileşen yalnızca bir kök öğesi olabilir.

Sen benim örnekte olduğu gibi .bind kullanın ve 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

Not kullanarak önleyebilirsiniz: Ek kök öğeyi atlama izin veren Fragments yoktur * 16. Tepki itibaren.

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

elbette! güzel çalıştı! Teşekkürler dostum!! –