簡體   English   中英

如何根據這些組件中定義的某些操作在頁面上呈現不同的組件?

[英]How do I render different components on a page according to some action defined inside those said components?

如果我有以下 App 組件:

function App() {
  if(test)
    return <Component1 />;
  else
    return <Component2 />;
}

但是test的值(真/假)取決於兩個各自組件內的按鈕。 單擊按鈕應翻轉test的值(即,如果為false ,則設置為true ,反之亦然)。 我將如何實現這一點?

您在 App 級別定義test並傳遞回調

function App() {
  let [test, setTest] = useState(false)
  if(test)
    return <Component1 setTest={setTest}/>;
  else
    return <Component2 setTest={setTest}/>;
}

組件內部,您可以實現翻轉邏輯,例如

props.setTest(ps=>!ps);

您的父組件應該具有 state 並為子組件提供適當的方法來更改 state。 @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組件包含 state,其中包含test屬性。 它還具有changeState function ,在 state 中進行切換test

changeState function 作為道具傳遞給子組件。 子組件調用 function 內部觸發父 function 和 state 更改:

function Component1(props) {
  return (<button onClick={props.onChangeState}>Component 1</button>);
}

這是演示

這有效:

function App() {
  const [test, setTest] = useState(false);

  const example = () => {
    setTest(!test);
  };

  if (!test) {
    return <Component1 example={example} />;
  } else {
    return <Component2 example={example} />;
  }
}

Component1 (和Component2 )內部:

function Component1(props) {
  return <button onClick={() => props.example()}>Click</button>;
}

直接將setTest作為道具傳遞是行不通的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM