Reactjs 我可以用函数组件传递ref吗?

Reactjs 我可以用函数组件传递ref吗?,reactjs,function,dom,components,Reactjs,Function,Dom,Components,-我正在使用功能组件。 -现在我在这里使用了3个组件,其中一个是父组件,另外2个是子组件。 -我需要访问一个子组件方法或另一个子方法的状态。我已经用CreateRef处理了类组件,但是现在我需要使用函数组件,但是我在“ref.current”中得到了Null 导出函数侧边列表(props){ const ref=React.createRef(); //这是成功后在ListPage内的调用 函数updateRightList(id){ ref.current.state.actualSearc

-我正在使用功能组件。 -现在我在这里使用了3个组件,其中一个是父组件,另外2个是子组件。 -我需要访问一个子组件方法或另一个子方法的状态。我已经用CreateRef处理了类组件,但是现在我需要使用函数组件,但是我在“ref.current”中得到了Null

导出函数侧边列表(props){
const ref=React.createRef();
//这是成功后在ListPage内的调用
函数updateRightList(id){
ref.current.state.actualSearchedModel.Id=Id
ref.current.fetchDataAndUpdate();
}
函数项(id){
updateRightList(id);
}
返回(
);

}
根据官方文件:

您不能在函数组件上使用ref属性,因为它们 没有实例

因此,如果您的
ListPage
是功能组件,则必须将其转换为类组件。或者您的ref必须引用
ListPage
中的DOM元素

function ListPage ({ref}) {
  return <div ref={ref}>Hello!</div>
}
函数列表页({ref}){
回敬你好!
}

更新:

函数父组件(){
const[state,setState]=React.useState(null);
const onChildMount=React.useCallback((dataFromChild)=>{
设置状态(dataFromChild);
});
返回(
{JSON.stringify(state,null,2)}
)
}
功能组件(道具){
const this应该传递给separant=“来自爱的孩子”;
React.useffect(()=>{
挂载道具(此道具应通过分路道具);
}, []);
返回(
子组件
)
}
ReactDOM.render(,document.querySelector(“#root”)

对于功能组件,您可以使用如下参考:

<TextField inputRef={input => input && input.focus()} />
//导入我们的钩子
从“React”导入React,{useRef,useffect};
//创建我们的参考
const myInput=useRef();
//这相当于我们的componentDidMount,这将集中
useffect(()=>myInput.current&&myInput.current.focus());
//将我们的ref解析为我们的textField
在这里你可以阅读文档

您也可以直接使用以下引用:

  class Parent extends React.Component {
     constructor(){
      this.setReferenceToElement = element => {
       this.fromChild = element;
      }
     }
     handleClick(){
       console.log(this.fromChild());
     }
    
     render(){
      return (
       <div>
         <Child setRef={this.setReferenceToElement} />
         <button onClick={handleClick}> Get state from child </button>
       </div>
      )
     }
    }
input&&input.focus()}/>

您可以在这里阅读全文:

如果有人正在寻找解决方案,其中
父组件
是类组件,
子组件
是功能组件,并且希望从
子组件
获取数据(状态,函数)

类组件:

function Child(props){
 // ... it has some state 
 props.setRef(state => state);
 return <div> Test </div>
}
类父级扩展React.Component{
构造函数(){
this.setReferenceToElement=元素=>{
this.fromChild=元素;
}
}
handleClick(){
console.log(this.fromChild());
}
render(){
返回(
从孩子那里得到状态
)
}
}
功能组件:

function Child(props){
 // ... it has some state 
 props.setRef(state => state);
 return <div> Test </div>
}
函数子(道具){
//…它有一些状态
props.setRef(state=>state);
回归试验
}

能否显示
列表页
组件代码?好的,知道了。但有没有办法在一个组件加载后将一个组件的函数用于另一个组件?是的,我认为你应该使用回调道具和生命周期方法来实现这一点。你能详细解释一下吗?我已经更新了我的答案。这段代码演示了如何在功能组件中使用回调道具和生命周期方法。是的,我使用了相同的方法,我使用了相同的方法,并且使用了相同的方法,将函数对象从子对象设置为父状态,然后从子对象调用更改后的调用。感谢您的精彩回复。从React 16+开始,这是此问题标题的正确答案。