我有一个显示和隐藏文本的切换按钮。当该按钮被单击时,我希望它隐藏另一个组件,如果再次单击,它将显示该组件。
我已在此处创建了一个epl:
https://repl.it/repls/DapperExtrasmallOpposites
我想保留原始的显示/隐藏文本,但我还想在单击按钮时隐藏另一个组件。
如何传递该状态,或者如何创建IF语句/三元运算符以测试它是处于显示状态还是隐藏状态。
以上Repl中的所有内容都有意义!
若要完成此操作,您应该将状态调高一点。可以将状态更改从切换组件传播到父组件,然后以任何方式使用它,但这不是首选方法。
如果将状态放在父组件中,则可以使用通过道具将其传递给所需的组件。
import React from "react";
export default function App() {
// Keep the state at this level and pass it down as needed.
const [isVisible, setIsVisible] = React.useState(false);
const toggleVisibility = () => setIsVisible(!isVisible);
return (
<div className="App">
<Toggle isVisible={isVisible} toggleVisibility={toggleVisibility} />
{isVisible && <NewComponent />}
</div>
);
}
class Toggle extends React.Component {
render() {
return (
<div>
<button onClick={this.props.toggleVisibility}>
{this.props.isVisible ? "Hide details" : "Show details"}
</button>
{this.props.isVisible && (
<div>
<p>
When the button is click I do want this component or text to be
shown - so my question is how do I hide the component
</p>
</div>
)}
</div>
);
}
}
class NewComponent extends React.Component {
render() {
return (
<div>
<p>When the button below (which is in another component) is clicked, I want this component to be hidden - but how do I pass the state to say - this is clicked so hide</p>
</div>
)
}
}