2016-09-21 24 views
0

考慮這個組件如何從複合組件中訪問html組件?

var React = require("react"); 

var Input = React.createClass({ 
    render:function(){ 
    return (<input {...this.props}/>) 
    } 
}) 

module.exports = Input; 

這是使用第一分量

var React = require('react'); 
var Button = require('./Button.react'); 
var Input = require('./Input.react'); 

var Form = React.createClass({ 
    render:function(){ 
    return(<div> 
     <Input ref = {(input) => this._user=input} placeholder='Username'/> 
     <Input ref = {(input) => this._pass=input} type="password" placeholder='Password'/> 
     <Button onClick={this.onPress}>Login</Button> 
    </div>) 
    }, 
    onPress:function(){ 
    console.log(this._user.value); 
    } 
}); 

module.exports = Form; 

我要訪問的第一個組件的<input />的值屬性的另一個組件。我知道只有組件構造函數在爲ref屬性提供的回調函數中可用。

那麼有什麼辦法可以訪問第二個組件內的html組件嗎?

我很抱歉,如果這個問題是重複的,我是新的反應和不熟悉的術語。

+0

'回調'可能會幫助你 –

+0

@TheReason你可以精心製作 – Abhishek

+0

@Abhishek你的用例是什麼?如果父母在大多數情況下需要訪問孩子,這是不好的設計。我發現自己問同樣的問題,然後找到更好的解決方案 – lustoykov

回答

2

您可以使用refs

<Input ref = {(input) => this._pass=input} type="password" placeholder='Password'/> 

然後

this._pass.yourValueFunction() 

不過,我懷疑這是不是你想要做什麼。您試圖從<Input />獲得值,但是應該使用<Input />onChange回調完成,該值在其父級中設置。

喜歡的東西...

var Input = React.createClass({ 
    render() { 
    return <input {...this.props} onChange={this.props.handleChange} /> 
    } 
}) 

,並在你的父母,你需要定義handleChange回調,例如

handleChange(e) { 
    this.setState({ inputValue: e.target.value }) 
    // or possibly this.inputValue = inputValue 
} 

,並把它傳遞給<Input />

<Input handleChange={handleChange} ... /> 

然後<Input />的值始終可以訪問:this.state.inputValue

+0

真棒工作...謝謝 – Abhishek

+0

@Ahhishek記住,這是React的方式,而不是一種解決方法。我強烈建議你閱讀下面的內容 - https://facebook.github.io/react/docs/thinking-in-react.html 快樂編碼;-) – lustoykov

+0

仔細一看,我發現該組件正在渲染我們在輸入字段中鍵入內容時,你確定這是做到這一點的方法嗎? – Abhishek

相關問題