2016-09-21 89 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