如何在React js中从另一个组件更改组件

问题描述 投票:0回答:3

我在Sidebar.js类中有一个补充工具栏。和Change.js类中的一个按钮我想在Change.js类中单击按钮更改/重新加载Sidebar.js我该怎么办,请帮忙。

reactjs react-component
3个回答
0
投票

Sidebar组件导入Change组件内,并且您必须为ref创建一个Sidebar,例如

<Sidebar ref={(ref) => { this.sideBar = ref; }} />

在侧边栏中,您必须具有一个功能doThis,并且必须使用在Change中创建的引用来触发该功能内部频道:

<div onClick={() => this.sideBar.doThis()}/>

您可以这样触发它。


0
投票

[您有两种选择,一种是Yuri的引用,使用redux,或者更好的useContext钩子。但是,如果您是新手,则有点复杂。然后,我建议使用将在这两个组件“之上”的状态。比您可以同时使用state和setState。工作示例:https://codesandbox.io/s/priceless-sun-vpims

import React, { useState } from "react";

const MyButton = ({ setClickState }) => (
  <button onClick={() => setClickState(p => p + 1)}>CLICK ME!</button>
);

const DivWhichReacts = ({ clickState }) => {
  return <div>{`Button was clicked ${JSON.stringify(clickState)} times`}</div>;
};

export default function App() {
  const [clickState, setClickState] = useState(0);
  return (
    <div className="App">
      <DivWhichReacts clickState={clickState} />
      <MyButton setClickState={setClickState} />
    </div>
  );
}

0
投票

您可以使用onClick on按钮并传递使用类似ReactDOM.render方法的函数引用...

<button href="JavaScript:Void(0);" onClick={myfunction}> ABC </button>

const myfunction= () => {
  ReactDOM.render(
    <Component />,
    document.getElementById("app-container")
  );
};

© www.soinside.com 2019 - 2024. All rights reserved.