【问题标题】:React Material UI | Passing Style Props to Components反应材料 UI |将样式道具传递给组件
【发布时间】:2019-04-27 03:32:24
【问题描述】:

如何根据按钮单击将样式道具传递给组件。因此,我有两个组件,一个称为按钮组件,另一个称为应答组件。我在按钮组件中有三个按钮。如果我们单击第一个按钮,它应该显示带有 BG 颜色蓝色的 Answer 组件。如果我单击按钮组件中的第二个按钮。它应该以 BG 颜色红色显示答案组件,反之亦然。我可以通过什么方式实现它。

提前致谢。

【问题讨论】:

  • 你是否让它与 react material-ui 一起工作?
  • 是的@gsalgadotoledo

标签: reactjs


【解决方案1】:

您可以通过在按钮组件中使用回调来传递样式,以向希望更改答案组件样式的父组件发出信号。

我们可以从拥有一个存储颜色状态的父组件开始。然后我们做一个回调函数给孩子,让它改变我们父母的颜色。状态。对于 answer 组件,我们只需将父组件的颜色状态发送到该组件以用于更改 BG 颜色。

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

  render() {
    return (
      <div className={`answer ${this.props.color}`}> Answer component </div>
    );
  }
}

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

  render() {
    return (
      <div>
        <button onClick={() => { this.props.changeColorCallback('blue'); }}>Change to BLUE</button>
        <button onClick={() => { this.props.changeColorCallback('red'); }}>Change to RED</button>
        <button onClick={() => { this.props.changeColorCallback('green'); }}>Change to GREEN</button>
      </div>
    );
  }
}

class Parent extends React.Component {

  constructor(props) {
      super(props);
      this.state = {
          color: 'red'
      };
  }

  changeColorCallback = (newColor) => {
      this.setState({ color: newColor });
  }

  render() {
    return (
      <div>
        <ChildAnswer color={this.state.color} />
        <ChildButtons changeColorCallback={this.changeColorCallback}/>
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Parent/>,
  document.getElementById("react")
);
button {
    margin: 0 10px;
}

.answer {
    width: 200px;
    height: 20px;
    margin: 10px;
    color: white;
    text-align: center;
    padding: 5px
}

.red {
    background-color: red;
}

.blue {
    background-color: blue;
}

.green {
    background-color: green;
}
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-17
    • 2021-12-27
    • 1970-01-01
    • 2021-12-10
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    相关资源
    最近更新 更多