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

时间:2018-10-05 10:40:41

标签: reactjs redux react-redux redux-form

我想连接2个不同的组件。 一个组件保持状态,另一个组件是呈现组件。 我想将每个类别的产品显示给CategoryContainer。但是我需要在ProductsList中具有categoryId才能显示产品,并为某些组件(例如TextBox,Dropdown)的适当属性设置正确的值。有任何想法吗?

保持状态的组件:

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;

Presentational组件:

class ProductLists extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expanded: false
    };
  }

  render() {
    return (
      <div>
      <TextBox/>
      <DropDownList />
      </div>
    );
  }
}

ProductLists.propTypes = {
};

export default ProductLists;

1 个答案:

答案 0 :(得分:1)

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

其次,在渲染函数中,您需要将值作为prop传递给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>
     );
  };
}

最后,为了在ProductList中查看categoryId和categotyName,您只需要显示它们即可。

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;