从另一个组件反应更新的无状态组件

时间:2019-10-30 02:59:43

标签: reactjs

export default function App() { return(<div><customButton/><customTable/></div>) }
export default function customButton() { return(<div><button>update</button></div>) }

由于该应用是父组件,而按钮和表是子组件。我知道这不是最佳做法,但是如何从按钮组件更新(重新渲染)表组件?

2 个答案:

答案 0 :(得分:1)

执行此操作的方法是在最接近的祖先处具有一些共享状态。在下面的示例中,我在value中创建一个App状态变量,并将其传递给customTable元素。我有一个setValue设置器,该设置器传递到customButton。单击按钮后,value会更新并传递给customTable,从而使表以该新值重新呈现。

export default function App() {
  const [value, setValue] = React.useState(0);
  return(
    <div>
      <customButton setValue={setValue} />
      <customTable value={value} />
    </div>
  )
}

export default function customButton({ setValue }) {
  return(
    <div>
      <button onClick={() => setValue(v => v + 1)}>update</button>
    </div>
  ) 
}

答案 1 :(得分:0)

使用自定义表格和自定义按钮对应用程序进行采样。

function CustomButton(props) {
  return <button onClick={props.addClick}>{props.children}</button>
}
function CustomTable({ table }) {
  return (
    <table>
      <thead>
        <tr>
          <th>No.</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
        {table.map((item, i) => (
          <tr key={i.toString()}>
            <td>{i.toString()}</td>
            <td>{item.name}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
function App() {
  const [input, setInput] = React.useState('')
  const [table, setTable] = React.useState([
    { name: "John" },
    { name: "Bukky" },
    { name: "Behem" }
  ]);
  const handleInput = e=>{
    setInput(e.target.value)
  }
  const addClick = e => {
    const update = [...table, { name: input }];
    setTable(update);
    setInput('')
  };
  return (
    <div>
      <input type="text" value={input} onChange={handleInput}/>
      <CustomButton addClick={addClick}>Click to Add</CustomButton>
      <CustomTable table={table} />
    </div>
  );
}