2016-06-22 16 views
1

ReactJSを手直しして簡単な例を扱っています。すごくうまくいっていて、私はすでに生産性が向上していると感じています。今、私はEnterキーが押されたときにアプリケーション名をコンソールに記録する簡単なReactの例を取り上げています。入力ボックスにアプリケーション名を入力してEnterキーを押すまで、すべて正常に動作しますが、コンソールログに表示されるのは入力値ではなく、「未定義」値です。ここには完全なJSコードがあります:Reactコンポーネントの小道具へのアクセス

"use strict"; 

var InputText = React.createClass({ 
    render() { 
     return <div><p>Please input the app name you wish to access:</p></div> 
    } 
}); 

var InputBox = React.createClass({ 
    onKeyPress(e) { 
     if (e.key === 'Enter') { 
     console.log(this.props.value); 
     } 
    }, 
    render() { 
     return <input type="text" onKeyPress={this.onKeyPress}></input> 
    } 
}); 

var AppForm = React.createClass({ 
    render() { 
     return <div class="appForm"> 
      <InputText /> 
      <InputBox /> 
     </div> 
    } 
}); 

var App = React.createClass({ 
    render() { 
     return <AppForm /> 
    } 
}); 

ReactDOM.render(
    <App />, 
    document.getElementById("container") 
); 

答えて

1

これは、値を小道具としてInputBoxコンポーネントに渡していないためです。

あなたがイベント

var InputBox = React.createClass({ 
    onKeyPress(e) { 
     if (e.key === 'Enter') { 
     console.log('InputBox Value: ' + e.target.value); 
     } 
    }, 
    render() { 
     return <input type="text" onKeyPress={this.onKeyPress}></input> 
    } 
}); 

jsfiddle

から値を取得したり、状態の値を格納し、そこからそれを得ることができます。

var InputBox = React.createClass({ 
    onKeyPress(e) { 
     if (e.key === 'Enter') { 
     console.log('InputBox Value: ' + this.state.value); 
     } 
    }, 
    render() { 
     return <input type="text" onKeyPress={this.onKeyPress} onChange={(e) => this.setState({value: e.target.value})}></input> 
    } 
}); 

jsfiddle

1

あなたはどんな小道具にも渡しませんでした。あなたが実際にこのアプリ:)

しかし、あなたが本当にしたいことは、入力ボックスから値があるのどこに渡された何の小道具がないこの

のような小道具を渡すでしょう。だから、Reactではリファレンスを作成します。間に合わせの一例として、私は、グローバルコンテキストオブジェクト私のコンポーネントで今ctx={}

<input type="text" className="inputClass" style={inputStyles} ref={(c) => ctx._input = c} /> 

を持って、私はそのCONSOLE.LOG

ctx._input.value 

として入力された値を参照することができますし、それはすべての良いことがあります。

1

使用入力ボックス

"use strict"; 

var InputText = React.createClass({ 
    render() { 
     return <div><p>Please input the app name you wish to access:</p></div> 
    } 
}); 

var InputBox = React.createClass({ 
    onKeyPress(e) { 
     if (e.key === 'Enter') { 
     console.log(this.refs.textbox.value); 
     } 
    }, 
    render() { 
     return <input type="text" onKeyPress={this.onKeyPress} ref = 'textbox'></input> 
    } 
}); 

var AppForm = React.createClass({ 
    render() { 
     return <div class="appForm"> 
      <InputText /> 
      <InputBox /> 
     </div> 
    } 
}); 

var App = React.createClass({ 
    render() { 
     return <AppForm /> 
    } 
}); 

ReactDOM.render(
    <App />, 
    document.getElementById("container") 
); 

JSFIDDLE

の値にアクセスするためのREF値を得るための別の方法は、イベントにEを使用するようになります 012として。 Propsは、あなたが実際にInputBoxコンポーネントに小道具を渡していないため動作しません。

関連する問題