2017-06-08 11 views
1

を持つ親のコールバックを呼び出すときにレンダリングするために失敗した反応します正しく表示されます。どうして?それは、イベントオブジェクトまたは親イベントハンドラが子イベントハンドラから呼び出されたという事実と関係がありますか?は、子コンポーネントは、私が親/子コンポーネントを持ってSETSTATE

+0

「レンダリングが正しく行われない」とはどういう意味ですか?それはレンダリングされるかどうか?何か変わるでしょうか?もしそうなら、何? – squgeim

+0

これは何ですか?this.setState( {値:e.target.value}、 ()=> this.props.onChange(e) ) '? – wesley6j

+0

@ wesley6jこれは、コンポーネントの状態を設定し、状態が実際に更新されたときに、親コンポーネントからpropとして渡された 'onChange'関数が呼び出されます。 'setState'は非同期で、2番目の引数は状態変更が適用されたときに呼び出されるコールバック関数です。 –

答えて

1

使用この(?前後にスペースを追加):

style={{backgroundColor: this.state.modified ? "red" : "blue"}} 

これに代えて:この後

style={{backgroundColor: this.state.modified?"red":"blue"}} 

正常に動作しますあなたの例を変更します。

class Input extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    this.state = {value: this.props.value}; 
 
    this.handleChange = this.handleChange.bind(this); 
 
    } 
 

 
    handleChange(e) { 
 
    // event is persisted, used to update local state 
 
    // and then call parent onChange callback after local state update 
 
    e.persist(); 
 
    this.setState(
 
     {value: e.target.value}, 
 
    () => this.props.onChange(e) 
 
    ); 
 
    } 
 

 
    render() { 
 
    return (<input style={this.props.style} onChange={this.handleChange} />); 
 
    } 
 
} 
 

 
class Page extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    this.state = {modified: false}; 
 
    this.handleChange = this.handleChange.bind(this); 
 
    } 
 

 
    handleChange(e) { 
 
    const {name, value} = e.target; 
 
    console.log(`${name}: ${value}`); 
 
    // the two line execute fine, and everything works ok 
 
    // but as soon as I add the bottom on, Input no longer updates! 
 
    this.setState({modified: true}); 
 
    } 
 

 
    render() { 
 
    return (
 
     <Input onChange={this.handleChange} 
 
       style={{backgroundColor: this.state.modified ? "red":"blue"}} 
 
     /> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <Page />, 
 
    document.getElementById('container') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="container"> 
 
    <!-- This element's contents will be replaced with your component. --> 
 
</div>

+0

残念ながら、それは動作しません。実際のコードでは、実際にはスタイルプロパティを完全に削除しました。this.props.onChange({modified:this.state.modified})のようなカスタムパラメータでthis.props.onChange(e)を置き換えてみました。 int onChange function適切な変更を加えましたが、問題は解決しません。親OnChangeでsetStateを呼び出すと、子オブジェクトのレンダリングができなくなります。そして、これは私が例えばテキストを入力すると、変更が反映されないということです。 –

+0

私の答えからコードスニペットを実行しましたか?それは正しく動作するようです。 –

+0

あなたが提供したサンプルは機能しますが、実際のコードとは99%同一であるため、外部の理由が必要ですが、1%(親の追加の状態パラメータ)には何もありませんこの動作を説明してください。非常に奇妙な。 –

関連する問題