首页 > 解决方案 > 在 React JS 中,我如何告诉父组件子组件发生了什么事?

问题描述

我有一个具有简单层次结构的 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;

标签: reactjs

解决方案


您通过道具将回调从父组件传递给子组件。

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>
    );
  }
}

然后你有你的 Child 组件。

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

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


推荐阅读