在 React JS 中,如何告诉父组件子组件发生了某些事情?

IT技术 reactjs
2021-05-19 01:17:50

我有一个具有简单层次结构的 React JS 应用程序:ContainingBox 包装了两个 InfoBox 组件。在此示例中,我只想告诉 ContainingBox 组件 1) 已单击某些内容,以及 2) 已单击了哪个 InfoBox(按标签名称)?

这是一些在我的浏览器中运行的基本代码,可以启动和运行这个问题。当您单击页面上的 InfoBox 元素之一时,它会在 console.log 中执行所有操作。

从本质上讲,我想要实现的是,当单击子 InfoBox 元素之一时,我希望 ContainingBox 更改状态(特别是渲染的边框颜色)。

我不确定这里的正确方向是什么。

我使用 React 16.10.2 构建了这个应用程序,但我很乐意阅读将我指向最新的“React 方式”思维的答案。

import React from 'react';

import styled from 'styled-components'
import './App.css';


const StyledInfoBox = styled.div`
  width: 100px;
  border: solid 1px green;
  padding: 10px;
  cursor: pointer;
`


class InfoBox extends React.Component {
  constructor({blurb}) {
    super()
    this.state = {
      label: (blurb ?  blurb.label : ""),
    }
    this.selectBox = this.selectBox.bind(this);
  }

  selectBox(e) {
    e.preventDefault()
    console.log("selectBox")

    // how do I tell the ContainingBox component 1) that something has been clicked,
    // and 2) which InfoBox (by label name) has been clicked?
  }

  render() {
    const {label} = this.state
    return (
      <StyledInfoBox onClick={this.selectBox} >
        {label}
      </StyledInfoBox>
    )
  }
}

class ContainingBox extends React.Component {
  render() {
    return (
      <div>
        <InfoBox key={1} blurb={{label: "Aenean malesuada lorem"}} />
        <InfoBox key={2} blurb={{label: "Lorem Ipsum dor ameet"}} />
      </div>
    )
  }
}

function App() {
  return (
    <div className="App">
      <ContainingBox />
    </div>
  )
}

export default App;
1个回答

你通过 props 将父组件的回调传递给子组件。

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  changeNameTo = (newName) => this.setState({name: newName})

  render() {
    return (
      <div>
      <h1>{this.state.name}</h1>
        <p>
          <Child callbackExample={this.changeNameTo} />
        </p>
      </div>
    );
  }
}

然后你有你的子组件。

class Child extends Component {
    render() {
      return(
        <div>
        <button onClick={() => this.props.callbackExample("Doggos")}>
        Click me
        </button>
      </div>)
    }
}

当您单击按钮时,将调用回调设置父级的状态,然后在父级重新渲染时反映该状态。