2017-03-23 96 views
1

我有一个智能组件和一个愚蠢组件,我需要引用位于我的智能组件中的转储组件中的元素: can我通过它道具或?React - 从哑组件(子)传递给智能组件(父)

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 }/> 
    } 
} 

回答

5

您可以使用callback syntax for refs

// 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} /> 
    } 
} 
+0

这个方法很好,谢谢! :) – Nick1R1

+0

我宁愿使用回调,而不是将ref传递给children组件,因为您持有对父组件的引用。对于简单的组件工作正常,但对于大/复杂的组件,根据最佳实践,您应该使用回调。 –

2

DOC

你不可以对功能部件使用ref属性,因为 他们没有实例。如果您需要引用该组件,则应该将该组件转换为类 ,就像您需要生命周期 方法或状态时一样。

所以我想,如果你想使用ref,你需要使用class

检查:https://github.com/facebook/react/issues/4936

相关问题