[英]How do I render different components on a page according to some action defined inside those said components?
If I have the following App component:如果我有以下 App 组件:
function App() {
if(test)
return <Component1 />;
else
return <Component2 />;
}
But the value of test
(true/false) is dependent on a button inside the two respective components.但是
test
的值(真/假)取决于两个各自组件内的按钮。 Clicking the button should flip the value of test
(ie set to true
if false
and vice versa).单击按钮应翻转
test
的值(即,如果为false
,则设置为true
,反之亦然)。 How would I implement this?我将如何实现这一点?
You define test
on App level and pass down a callback您在 App 级别定义
test
并传递回调
function App() {
let [test, setTest] = useState(false)
if(test)
return <Component1 setTest={setTest}/>;
else
return <Component2 setTest={setTest}/>;
}
inside the component you can implement the flipping logic like在组件内部,您可以实现翻转逻辑,例如
props.setTest(ps=>!ps);
Your parent component should should have a state and provide child components with a proper way to change that state.您的父组件应该具有 state 并为子组件提供适当的方法来更改 state。 Similar implementation as @gmoniava provided but without hooks may look like below:
与@gmoniava提供但没有钩子的类似实现可能如下所示:
class App extends React.Component {
constructor(props) {
super(props)
this.changeState = this.changeState.bind(this);
this.state = {
test: false
}
}
changeState() {
this.setState({ test: !this.state.test });
}
render() {
const { test } = this.state;
return (
<div>
{test && <Component1 onChangeState={this.changeState} />}
{!test && <Component2 onChangeState={this.changeState} />}
</div>
)
}
}
App
component contains state with test
property in it. App
组件包含 state,其中包含test
属性。 Also it has changeState
function which toggle test
in state.它还具有
changeState
function ,在 state 中进行切换test
。
changeState
function is passed to child components as props. changeState
function 作为道具传递给子组件。 Child component calls that function inside which triggers parent function and state is changed:子组件调用 function 内部触发父 function 和 state 更改:
function Component1(props) {
return (<button onClick={props.onChangeState}>Component 1</button>);
}
This works:这有效:
function App() {
const [test, setTest] = useState(false);
const example = () => {
setTest(!test);
};
if (!test) {
return <Component1 example={example} />;
} else {
return <Component2 example={example} />;
}
}
and inside Component1
(and Component2
):在
Component1
(和Component2
)内部:
function Component1(props) {
return <button onClick={() => props.example()}>Click</button>;
}
Passing setTest
directly as prop didn't work.直接将
setTest
作为道具传递是行不通的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.