[英]React pass child class method to parent functional component
I am trying to get adaptValue
from Component1
and use it in Component2
.我正在尝试从Component1
获取adaptValue
并在Component2
中使用它。 For some reason this does not work since my adaptValue
is always null/undefined.由于某种原因,这不起作用,因为我的adaptValue
始终为空/未定义。 Is it because Parent
is a functional component?是因为Parent
是一个功能组件吗?
const Parent = (props) => {
const [adaptValue, setAdapt] = useState(null);
return (
<div>
<Component1 setAdapt={setAdapt}/>
<Component2 adaptValue={adaptValue}/>
</div>
)
}
export default class Component1 extends Component {
constructor(props) {
super(props);
}
adaptValue = (value) =>{
DO_SOMETHING_WITH_VALUE
}
componentDidMount() {
this.props.setAdapt(this.adaptValue);
}
render() {
return something;
}
}
export default class Component2 extends Component {
constructor(props) {
super(props);
}
someFunction = (value) =>{
...
//adaptValue is always undefined
this.props.adaptValue(value)
...
}
render() {
return something;
}
}
UPDATE Made the parent a class component in the end and all works.更新最终使父组件成为 class 组件并且一切正常。 Wondering whether this is a compatibility issue between functional or class-based components.想知道这是否是功能组件或基于类的组件之间的兼容性问题。
When passing setAdapt
to Component1
... setAdapt
is already a function.当将setAdapt
传递给Component1
... setAdapt
已经是 function。 There is no need to wrap it in another one.无需将其包裹在另一个中。 Component1
will modify the value, and Component2
will display it. Component1
将修改该值,而Component2
将显示它。 Function Components have nothing to do with the behavior. Function 组件与行为无关。
Try...尝试...
App.js应用程序.js
import React, { useState } from "react";
import "./styles.css";
import Component1 from "./Component1";
import Component2 from "./Component2";
export default function App() {
const [adaptValue, setAdapt] = useState(null);
return (
<div>
<Component1 setAdapt={setAdapt} />
<Component2 adaptValue={adaptValue} />
</div>
);
}
Component1.js组件1.js
import React, { Component } from "react";
export default class Component1 extends Component {
handleClick = () => {
this.props.setAdapt("New Value");
};
render() {
return <button onClick={() => this.handleClick()}>Set Value</button>;
}
}
Component2.js组件2.js
import React, { Component } from "react";
export default class Component2 extends Component {
render() {
return !!this.props.adaptValue ? (
<h1>{`"${this.props.adaptValue}" <- Value of adaptValue`}</h1>
) : (
<h1>adaptValue Not Assigned</h1>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.