Nic*_*1R1 10 ref reactjs redux
我有一个智能和一个哑组件,我需要引用我的智能组件中的转储组件中的元素:我可以用道具传递它吗?
Dumb:
export default (props)=>{
return(
<input type='number' ref='element'}/>
);}
Smart:
class Parent extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const node = this.refs.element; // undefined
}
render(){
return <Dumb { ...this.props }/>
}
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*imo 31
// Dumb:
export default props =>
<input type='number' ref={props.setRef} />
// Smart:
class Parent extends Component {
constructor(props) {
super(props);
}
setRef(ref) {
this.inputRef = ref;
}
render(){
return <Dumb {...this.props} setRef={this.setRef} />
}
}
Run Code Online (Sandbox Code Playgroud)
bbr*_*inx 10
使用 react^16.0.0,您将使用 React.createRef()。使用@Timo 的回答,它看起来像这样:
// Dumb:
export default props =>
<input type='number' ref={props.setRef} />
// Smart:
class Parent extends Component {
constructor(props) {
super(props);
this.ref1 = React.createRef()
}
render(){
return <Dumb {...this.props} setRef={this.ref1} />
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16001 次 |
| 最近记录: |