我对发送点击值到第一个兄弟组件有疑问,我将发送props值到第二个兄弟组件,这是可能的吗?
我有一个模块,当我单击第一个兄弟姐妹的类别项目时,第二个兄弟姐妹上的产品将根据我单击第一个兄弟姐妹的类别名称更改。
这是我的父组件:
function BuyerCategoryPage(props) {
return (
<div>
<CategorySlider />
<CategoryProducts/>
</div>
)
}
export default BuyerCategoryPage
First Sibling CategorySlider.js:
const HandleChangeProductCat = (value) => {
console.log(value);
// send the value to the second sibling
}
return (
<div>
<Container fluid>
<Slider style={{paddingTop:20, margin: '0 auto'}} {...settings}>
{
SlideData.map((data) => {
return (
<div key={data.id} >
<div className="sliderDataCategory">
<h6>
<Container>
<Row>
<Col md={3}>
<img className="img-fluid" src={data.cat_image} />
</Col>
<Col >
<label onClick={() => HandleChangeProductCat(data.cat_title)}>{data.cat_title}</label>
</Col>
</Row>
</Container>
</h6>
</div>
</div>
)
})
}
</Slider>
</Container>
</div>
)
Second Sibling categories .js
function CategoryProducts(props) {
}
最简单的方法是将state提升到BuyerCategoryPage
组件中,并传递一个"onChange"处理程序为CategorySlider
,状态值为CategoryProducts
function BuyerCategoryPage(props) {
const [state, setState] = React.useState(); // common state
return (
<div>
<CategorySlider onChange={setState} /> // pass updater function
<CategoryProducts value={state} /> // pass state value
</div>
);
}
CategorySlider
const handleChangeProductCat = (value) => {
console.log(value);
props.onChange(value); // invoke callback and pass new value
}
CategoryProducts
function CategoryProducts({ value }) { // access the passed value
// use the `value` prop as necessary
}
例如:
function Example() {
const [value, setValue] = useState("");
const onClick = (someValue) => {
setValue(someValue);
}
return (
<div>
<First onClick={onClick} />
<Second value={value} />
</div>
)
}
function First(props) {
const onClick = () => {
props.onClick((new Date()).toString());
}
return (
<input type="button" onClick={onClick} value="Click me" />
)
}
function Second(props) {
return (
<div>{props.value}</div>
)
}