【问题标题】:React pose state affects child component posesReact 姿势状态影响子组件姿势
【发布时间】:2019-03-07 15:05:24
【问题描述】:

我正在尝试在 react 中创建一个组件,它会在需要时折叠和展开。为此,我正在使用 react-pose。但是,我在尝试嵌套多个此组件时遇到了问题。

这是我定义组件的方式:

const CollapsableDiv = posed.div({
  show: {
    height: 'auto',
    overflow: 'hidden'
  },
  hide: {
    height: '0px',
    overflow: 'hidden'
  }
});

这就是我使用它的地方。

class App extends React.Component {
  state = { 
    showing: false, 
    showingInner: false 
  };

  toggleShow = () => this.setState({
    showing: !this.state.showing
  });

  toggleInner = () => this.setState({
    showingInner: !this.state.showingInner
  });

  render() {
    return (
      <React.Fragment>
        <button onClick={this.toggleShow}>
          {this.state.showing?'Hide':'Show'}
        </button>
        <CollapsableDiv pose={ this.state.showing ? 'show' : 'hide' }>
          <div>
            This is some content
            <button onClick={this.toggleInner}>
              {this.state.showingInner ? 'Hide' : 'Show'}
            </button>
            <CollapsableDiv pose={this.state.showingInner ? 'show' : 'hide'}>
              <div>
                This is some inner content    
              </div>
            </CollapsableDiv>
          </div>
        </CollapsableDiv>
      </React.Fragment>
    );
  }
}

我遇到的问题是外部&lt;CollapsableDiv&gt;“姿势”似乎传递给了内部,这意味着当您扩展外部 div 时,内部 div 也会扩展。内部&lt;CollapsableDiv&gt; 似乎对外部没有同样的影响。

这是问题的一个例子https://codesandbox.io/s/x7nljvom9z?fontsize=14

我在这里做错了吗?不能重复使用相同的组件吗?

【问题讨论】:

    标签: javascript reactjs react-pose


    【解决方案1】:

    使其与第二个CollapsableDiv 上的父集withParent={false}“独立”。例如:

    <CollapsableDiv
      pose={this.state.showingInner ? "show" : "hide"}
      withParent={false}
    >
      <div key="two">This is some inner content</div>
    </CollapsableDiv>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 2013-02-15
      • 2020-11-16
      • 1970-01-01
      • 2015-11-25
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多