如何连接保存状态的组件和表示组件?



我想连接 2 个不同的组件。 一个组件保存状态,另一个组件是表示组件。 我想向类别容器显示每个类别的产品。但是我需要在产品列表中具有 categoryId 来显示产品,并将正确的值设置为某些组件(如文本框、下拉列表(的适当属性。有什么想法吗?

保存状态的组件:

render() {
const {
categoryId,
categoryName
} = this.props;
return (
<MainComponent>
<label>Your categoryId is: </label>
{categoryId}
<label>Your categoryName is: </label>
{categoryName}
<label>The products of this category are: </label>
<div>
<ProductLists />
</div>
</MainComponent>
};
}

const mapStateToProps = (state, ownProps) => {
return {
categoryName:
selectAttributelById(state, ownProps.categoryId) &&
selectAttributelById(state, ownProps.categoryId).get("categoryName")
};
};
CategoryContainer = connect(
mapStateToProps
)(toJS(CategoryContainer));
CategoryContainerWrapped.propTypes = {
categoryName: PropTypes.bool
};
export default CategoryContainer;

表现组件:

class ProductLists extends Component {
constructor(props) {
super(props);
this.state = {
expanded: false
};
}
render() {
return (
<div>
<TextBox/>
<DropDownList />
</div>
);
}
}
ProductLists.propTypes = {
};
export default ProductLists;

首先,您需要阅读有关 react 以及如何在组件之间传递值作为 props 的更多信息。

其次,在渲染函数中,您需要将值作为道具传递给 ProductList 组件。

render() {
const {
categoryId,
categoryName
} = this.props;
return (
<MainComponent>
<label>Your categoryId is: </label>
{categoryId}
<label>Your categoryName is: </label>
{categoryName}
<label>The products of this category are: </label>
<div>
<ProductLists categoryId={categoryId} categoryName={categoryName} />
</div>
</MainComponent>
);
};
}

最后,为了在产品列表中查看类别ID和分类名称,您只需要显示它们。

class ProductLists extends Component {
constructor(props) {
super(props);
this.state = {
expanded: false
};
}
render() {
return (
<div>
CategoryId: {this.props.categoryId}
CategoryName: {this.props.categoryName}
<TextBox/>
<DropDownList />
</div>
);
}
}
ProductLists.propTypes = {
categoryId: PropTypes.number,
categoryName: PropTypes.string
};
export default ProductLists;

相关内容

最新更新