我想做一个if语句。单击prop函数时(按OK按钮时),我要渲染ComponentA,否则要渲染ComponentB。 组件B包含“确定”按钮,我作为函数将其传递给它。 我的if条件无法正常运作。有任何想法吗? 我的代码:
clickButton() {
console.log("yeah");
}
render() {
const {
clickButton
} = this.props;
return this.clickButton ? (
<ComponentA/>
) : (
<ComponentB clickButton={clickButton}/>
);
}
}
Example.propTypes = {
clickButton: PropTypes.func
};
答案 0 :(得分:1)
不确定这是否是您要寻找的东西
state = { clicked: false }
clickButton = () => {
console.log("yeah");
this.setState({clicked: !this.state.clicked})
}
render() {
const { clicked } = this.state;
return clicked ? (
<ComponentA/>
) : (
<ComponentB clickButton={this.clickButton}/>
);
}
}
如果您想要该组件之外的状态:
clickButton = e => {
console.log("yeah");
// so you will edit the value "clicked" passed as prop in the parent component
this.props.clickButton(e)
}
render() {
const { clicked } = this.props;
return cicked ? (
<ComponentA/>
) : (
<ComponentB clickButton={this.clickButton}/>
);
}
}
答案 1 :(得分:0)
您需要通过组件传递状态值,这样才能捕获更改后的事件,方法如下
state = {
isButtonClicked: false
}
clickButton = () => {
this.setState({ isButtonClicked: true })
}
render() {
return (
<Child isButtonClicked={this.state.isButtonClicked} clickButton={this.clickButton} />
)
}
render() {
const {
isButtonClicked,
clickButton
} = this.props
return this.isButtonClicked ? (
<ComponentA/>
) : (
<ComponentB clickButton={clickButton}/>
)
}
Example.propTypes = {
isButtonClicked: PropTypes.bool,
clickButton: PropTypes.func
}