单击“是”或“否”时,我试图隐藏组件。单击时我得到的输出正确,但是充当弹出窗口的组件保留在屏幕中,我无法删除它。
这是我的组成部分
export default class MyPopUp extends React.Component {
constructor(props) {
super(props)
}
render() {
let { username } = this.props
return (
<div className="modal-wrapper">
<div className="modal">
Some Text
<br />
<MyButton
name={username}
surname="pewlas"
arguments={["yes"]}
>
[ Yes ]
</PostCommandButton>{" "}
<MyButton
name={username}
surname="pewlas"
arguments={["no"]}
>
[ No ]
</MyButton>{" "}
</div>
</div>
)
}
}
这是MyButton
import { connect } from "react-redux"
import button from "../../../common/components/Button"
import { myButton } from "../actions/myButton"
const MyButton = connect(
undefined,
(dispatch, { name, surname, arguments: args = [] }) => ({
onClick: () => dispatch(button(name, username, args)),
}),
)(Button)
export default MyButton
这是我的按钮
export const MY_BUTTON = "MY_BUTTON"
export const myButton = (name, surname, args) => ({
type: MY_BUTTON,
name,
surname,
arguments: args,
})
当单击“是”或“否”时,如何隐藏MyPopUp
?我找不到将My PopButton组件与MyButton的onClick链接的方法,如何添加状态以便可以显示它呢?
答案 0 :(得分:1)
我将尽力帮助您重构一些代码。
首先,我已经看到您正在将Redux与Button一起使用,以执行您想做的事情,您有一些选择:
const SURNAME = "pewlas"
export class MyPopUpComponent extends React.Component {
state = { hidden: false }
handleClick = value => {
this.props.myButton(this.props.username, SURNAME, value) //the action creator
this.setState({ hidden: true }) //**IMPORTANT**
}
render() {
const { username } = this.props
if (this.state.hidden) {
return null
}
return (
<div className="modal-wrapper">
<div className="modal">
Some Text
<br />
<button
name={username}
surname={SURNAME}
onClick={() => this.handleClick("yes")}
>
[ Yes ]
</button>{" "}
<button
name={username}
surname={SURNAME}
onClick={() => this.handleClick("no")}
>
[ No ]
</button>{" "}
</div>
</div>
)
}
}
const mapDispatchToProps = {
myButton
}
export const MyPopUp = connect(null, mapDispatchToProps)(MyPopUpComponent)
您可以执行类似的操作,首先,显示隐藏为false的弹出窗口初始化状态。正如您在渲染中看到的那样,您将使用按钮显示文本,并且当用户按Yes或现在您可以启动动作或执行所需的任何操作后,将hidden设置为true。状态已更改,因此再次调用render函数,并返回null,从而隐藏了该组件。
希望它对您有帮助