隐藏组件以更改其状态,即redux反应

时间:2018-12-09 14:57:46

标签: javascript reactjs redux react-redux

我创建了一个组件,试图在单击按钮时更改其状态,但是我不知道为什么我没有收到此更改... 我的组件使用Button,它是另一个组件,所以我需要的是单击此Button时要更改PopUp组件的状态(我要隐藏的组件)并将其从用户界面中删除。

这是我的Button组件,但是我不能更改也不能修改它,所以我应该修改新组件

const MyButton = connect(
  undefined,
  (dispatch, { name, surname, arguments: args = [] }) => ({
    onClick: () => dispatch(myButton(name, surname, args)),
  }),
)(Button)

export default MyButton

所以,减速器是

export const MY_BUTTON = "MY_BUTTON"
export const myButton = (name, surname, args) => ({
  type: MY_BUTTON,
  name,
  surname,
  arguments: args,
})

好,现在我想做的PopUp组件是:

export default class PopUp extends React.Component {
  state = { hidden: false }

  handleClick = value => {
    this.setState({ hidden: true })
  }

  render() {
    let { name } = this.props
    if (this.state.hidden) {
      return null
    }

    return (
      <div className="modal-wrapper">
        <div className="modal">
          SomeText
          <br />
          <MyButton
            name={name}
            surname="example1"
            arguments={["yes"]}
            onClick={() => this.handleClick("yes")}
          >
            [ Yes ]
          </MyButton>{" "}
          <MyButton
            name={name}
            surname="example2"
            arguments={["no"]}
            onClick={() => this.handleClick("no")}
          >
            [ No ]
          </MyButton>{" "}
        </div>
      </div>
    )
  }
}

那么,当我单击“是”或“否”时,为什么它不关闭弹出窗口?

我正在如下创建此Component

{showPopUp && <PopUp name={name} />}

一个人告诉我,我可以在div内创建一个onClick,然后在div内创建按钮,以便我检测到两个onClick,这有可能吗?

1 个答案:

答案 0 :(得分:0)

如果要隐藏组件,请尝试以下操作:

export default class PopUp extends React.Component {
  state = { 
     hidden: false,
  }

handleClick = () => {
 this.setState({ 
   hidden: true,
 })
}
render() {
  const { name } = this.props;
  const { hidden } = this.state;

 return (
  <div className="modal-wrapper">
  { !hidden  && 
    <div className="modal">
      SomeText
      <br />
      <MyButton
        name={name}
        surname="example1"
        arguments={["yes"]}
        onClick={() => this.handleClick}
      >
        [ Yes ]
      </MyButton>{" "}

      <MyButton
        name={name}
        surname="example2"
        arguments={["no"]}
        onClick={() => this.handleClick}
      >
      [ No ]
      </MyButton>{" "}
    </div>
  }
  </div>
)
}
}

然后尝试像这样重构调度程序:

const mapDispatchToProps = dispatch => ({
  dispathMethod: (name, surname, args) => dispatch(name, surname, args)), 
})

//if you are using selector use it:

const mapStateToProps = createStructuredSelector({
  accessories: selectSomething(),
});


const withConnect = connect(
 //here(1st param)if selecter using put ? mapStateToProps : null 
  mapDispatchToProps,
);

export default compose(
  null,
  withConnect,
)(Button);