【问题标题】:function uses this.state and pass it to another component函数使用 this.state 并将其传递给另一个组件
【发布时间】:2021-09-19 01:26:33
【问题描述】:

大家好,问题很简单。我有一个类组件,里面有两种颜色的状态。 我想创建一个 onClick 函数,当您单击它时,它会显示来自 this.state 的 2 个带有 backgroundColors 的 div。 并且按钮 MOST 在父级上 这里是代码

class Parent extends React.Component{
constructor(props){
    super(props);

this.state = {
color1: "#38306b",
color2: "#fff285"
}

saveColors() = {
// thats the part i dont get.

render(){
return(
  <Child />
  <button onClick={() => saveColors()}>save</button>
)



class Child extends React.Component{

render(){
return(
   //those divs need to appear when we click the button with saveColors().
   <div style={{backgroundColor: color1 from Parent's state}}></div>
   <div style={{backgroundColor: color2 from Parent's state}}></div>
)

我可以将 this.state.color1 放入一个 var 并在子组件中使用它吗?还是我应该使用返回?还是别的什么??

【问题讨论】:

  • 您的代码 sn-ps 没有意义,请分享正确的代码。

标签: reactjs


【解决方案1】:

您需要在 Parent 中声明以检查单击的按钮。并将值从Parent 传递给Child

this.state = {
  color1: "#38306b",
  color2: "#fff285",
  isClicked: false,
}

saveColors = () => {
  this.setState({isClicked: true})
}

<Child color1={this.state.color1} color2={this.state.color2} isClicked={this.state.isClicked} />

在 `Child:

return (
  ...
  {this.props.isClicked && (
    <>
      <div style={{backgroundColor: this.props.color1}}></div>
      <div style={{backgroundColor: this.props.color2}}></div>
    </>
  )}
)

【讨论】:

  • 是的,但我需要它与 onClick 功能一起发生):这就是我迷路的原因
  • 我想这是你在过去一周里第二次救了我!谢谢!
【解决方案2】:

您可以将状态作为道具传递给 Child

class Main extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      color1: "#38306b",
      color2: "#fff285"
    }
  }

  saveColors() {
  }


  render() {
    return (
      <div style={{ flex: 1, backgroundColor: 'red' }}>
        <Child color={this.state} />
        <button onClick={() => this.saveColors()}>save</button>
      </div>
    )
  }
}

class Child extends React.Component {


  render() {
    return (
      <>
        <div style={{
          flex: 1,
          backgroundColor: this.props.color.color1,
          height: 400
        }}>
          DIV1
        </div>
        <div style={{
          flex: 1,
          backgroundColor: this.props.color.color2,
          height: 400
        }}>
          DIV2
        </div>
      </>
    )
  }
}

如果您想在单击按钮时更改颜色,只需使用 setState 更改状态

  saveColors() {
    this.setState({
      color1: 'blue',
      color2: 'red'
    })
  }

【讨论】:

    猜你喜欢
    • 2019-11-12
    • 2018-08-31
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 2017-07-27
    相关资源
    最近更新 更多