Reactjs 将数据从功能组件发送到父组件
我有以下功能组件,它呈现3个复选框(Shopify Polaris):Reactjs 将数据从功能组件发送到父组件,reactjs,react-hooks,react-component,react-functional-component,Reactjs,React Hooks,React Component,React Functional Component,我有以下功能组件,它呈现3个复选框(Shopify Polaris): 函数CustomersList(){ const[selected,setSelected]=useState(['hidden']); const handleChange=useCallback((值)=>setSelected(值),[]); 返回( ); } 。。。同样的功能。组件在父组件中使用(两者在同一文件中): 类ParentComponent扩展组件{ render(){ 返回( 所选客户:{custome
函数CustomersList(){
const[selected,setSelected]=useState(['hidden']);
const handleChange=useCallback((值)=>setSelected(值),[]);
返回(
);
}
。。。同样的功能。组件在父组件中使用(两者在同一文件中):
类ParentComponent扩展组件{
render(){
返回(
所选客户:{customer_value}
)
}
}
现在,我的问题是如何从func发送和获取客户值(customer1、customer2等)。组件到父组件,在此处显示值:所选客户:{customer\u value}
谢谢您可以向
客户列表
发送回调,该列表将向调用者附加一些数据。所以您的父组件可能看起来像这样
class ParentComponent extends Component {
state = {
selection: []
}
setSelection(data) {
this.setState({selection: data});
}
render() {
return (
<Page title="Title">
<Layout>
<Layout.Section>
<Card title="Customers" sectioned>
<CustomersList setSelection={this.setSelection}/>
<Subheading>
Selected customers: {customer_value}
</Subheading>
</Card>
</Layout.Section>
</Layout>
</Page>
)
}
}
这应该就可以了。您能告诉我如何在handleChange函数中调用setSelection吗?我尝试了不同的方法,但无法使其工作?谢谢
class ParentComponent extends Component {
render() {
return (
<Page title="Title">
<Layout>
<Layout.Section>
<Card title="Customers" sectioned>
<CustomersList />
<Subheading>
Selected customers: {customer_value}
</Subheading>
</Card>
</Layout.Section>
</Layout>
</Page>
)
}
}
class ParentComponent extends Component {
state = {
selection: []
}
setSelection(data) {
this.setState({selection: data});
}
render() {
return (
<Page title="Title">
<Layout>
<Layout.Section>
<Card title="Customers" sectioned>
<CustomersList setSelection={this.setSelection}/>
<Subheading>
Selected customers: {customer_value}
</Subheading>
</Card>
</Layout.Section>
</Layout>
</Page>
)
}
}
function CustomersList(setSelection) {
const [selected, setSelected] = useState(['hidden']);
const handleChange = // Update your handleChange to also call setSelection