React与其他组件通信

时间:2017-06-08 16:06:50

标签: reactjs

我有这些组件" Portlet"," PortletTitle"," PortletTool"," PortletBody" 。一切正常,但现在我想在组件之间添加一个简单的交互。

在我的应用中使用:

<Portlet>
  <PortletTitle>
    <PortletTool toolCollapse={true}>
  </PortletTitle>
  <PortletBody>bla vla bla </PortletBody>
</Portlet>

PortletTool.js

class PortletTools extends React.Component {

    static propTypes = { toolCollapse: PropTypes.bool };
    state = { collaped: false };

    handler = () => {
        let newstate = !this.state.collaped;
        this.setState({ collaped: newstate });
    };

    render() {
        const classCollaped = !this.state.collaped ? "collapse" : "expand";
        let toolCollapse = this.props.toolCollapse
            ? <a href="javascript:;" className={classCollaped} title="" data-original-title="" onClick={this.handler}>{" "}</a>
            : "";

        return (
            <div className="tools">
                {toolCollapse}
            </div>
        );
    }
}

PortletBody有一个道具&#34; showbody&#34;隐藏/显示元素,但我现在可以使用此结构(已在其他应用程序页面中使用)单击我的PortletTool e隐藏/显示我的PortletBody?是的,怎么样?

我必须(如果可能的话)在&#34; Portet&#34;成分

1 个答案:

答案 0 :(得分:0)

如果您想在任何子组件之间添加一些互动,那么您将处于对lift state up.有帮助的位置。在这种情况下,您希望将折叠状态向上移动到您的Portlet组件,注册一个处理程序,用于更改Portlet类中的状态,绑定上下文,并将该处理程序传递给PortletTool.您还希望传递collapsed通过PortletBodyprops申请。

例如:

class Portlet extends React.Component {
  state={collaped:false};
    handler=()=>{
    let newstate=!this.state.collaped;
    this.setState({collaped:newstate});
    }

   render() {
    return (
      <PortletTitle>
          <PortletTool handler={this.handler}>
        </PortletTitle>
        <PortletBody collapsed={this.state.collapsed}>bla vla bla </PortletBody>
      )
   }
}

然后将处理程序分配给PortletTool中某处的onClick道具。如果您收到cannot read property of undefined错误,则需要bind the context to the handler