![](/img/trans.png)
[英]How to pass value from a child functional component to parent class component?
[英]Is it possible pass from functional child component reference to Parent(Class pure component)
我有一個項目,我需要將 class 組件更改為功能組件,但項目正在使用引用來訪問子組件,是否可以將功能子組件的引用提供給 Class 父組件?
例如
const ChildComponent = ({ ref }) => {
return (
<div>Child component</div>
)
}
class TodoApp extends React.Component {
ref;
componentDidMount(){
console.log(this.ref);
}
render(){
return(
<ChildComponent ref={this.ref}/>
)
}
}
是的,您將使用鈎子 useImperativeHandle。
https://reactjs.org/docs/hooks-reference.html#useimperativehandle
const ChildComponent = (props, ref) => {
useImperativeHandle(ref, () => ({
key: "value"
}))
return <div>Child component</div>
}
ChildComponent = forwardRef(ChildComponent)
是的,您可以使用回調將數據從子組件傳遞到父組件,即
const ChildComponent = ({
callback
}) => {
callback('data to be passed to parent component')
return ( <
div > Child component < /div>
)
}
class TodoApp extends React.Component {
state = {
ref: ''
}
componentDidMount() {
console.log(this.state.ref);
}
render() {
return ( <
ChildComponent callback = {
(ref) => this.setState(ref)
}
/>
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.