考虑这个组件
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 />
的 value 属性第一个组件的。据我所知,为 ref 属性提供的回调函数中只有组件构造函数可用。
那么有什么方法可以访问第二个组件中的 html 组件吗?
如果这个问题重复,我深表歉意,我是新手,不熟悉术语。
最佳答案
您可以使用refs
<Input ref = {(input) => this._pass=input} type="password" placeholder='Password'/>
然后
this._pass.yourValueFunction()
<小时/>
但是,我怀疑这不是您想要做的。您正在尝试从 <Input />
获取值,但这应该用 onChange
来完成来自 <Input />
的回调这就是在其父级中设置值。
类似...
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
关于javascript - 如何从react中的复合组件访问html组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39610101/