2017-03-23 34 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

相關問題