有条件的内联式基于prop的反应组件

时间:2017-09-15 01:43:10

标签: css reactjs conditional

我需要根据传入反应组件的道具设置div的背景颜色。 React组件的内联样式我很清楚,但我不知道如何正确应用内联样式来根据prop进行更改。如果道具rightSideColor相等right-toggle,我只想在selected的内联样式中指定道具true的值。

export default function UiToggle(props) {
  const { leftLabel, rightLabel, selected, rightSideColor, leftSideColor } = props;

  return (
    <div className="lr-toggle-select" style={{ width: `${width}px` }} >
      <div className="lr-gray-background" />
      <div>
        {leftLabel}
      </div>
      <div className={'lr-toggle right-toggle' style={{ selected ? (backgroundColor: rightSideColor) : null }}>
        {rightLabel}
      </div>
    </div>
  );
}

3 个答案:

答案 0 :(得分:2)

我建议将所有样式和条件运算符放在一个单独的const中。

export default function UiToggle(props) {

  const { leftLabel, rightLabel, selected, rightSideColor, leftSideColor } = props;

  const rightToggleStyle = {
     backgroundColor: selected ? rightSideColor : null
  };

  return (
    <div className="lr-toggle-select" style={{ width: `${width}px` }} >
      <div className="lr-gray-background" />
      <div>
        {leftLabel}
      </div>
      <div className="lr-toggle right-toggle" style={rightToggleStyle}>
        {rightLabel}
      </div>
    </div>
  );
}

我会尝试对宽度的样式做同样的事情。祝你好运!

答案 1 :(得分:1)

您可以有条件地设置样式等属性的值,使用优先级规则覆盖它们,并确定是否完全包含它们。

export default function UiToggle(props) {
  const { leftLabel, rightLabel, selected, rightSideColor, leftSideColor } = props;
  //specify style and id (and any other attributes) or don't.
  const attrs = selected ? { style: { backgroundColor: "rightSideColor" },id:"hi123" }:{}
  //Conditionally override the class names if we want:
  if (props.className) attrs.className = props.className

  return (
    <div className="lr-toggle-select" style={{ width: `${width}px` }} >
      <div className="lr-gray-background" />
      <div>
        {leftLabel}
      </div>

      {/*Use the spread operator to apply your attributes from attr*/}
      {/*Note that the 'id' set below can't be overridden by attrs whereas*/}
      {/*className will be. That's because precedence goes from right to left.*/}           
      {/*Rearrange them to get what you want.*/}
      {/*Funky comment format is to make valid JSX and also make SO formatter happy*/}          

      <div className='lr-toggle right-toggle' {...attrs} id="attrs_cant_override_this_because_its_on_the_right">
        {rightLabel}
      </div>
    </div>
  );
}

答案 2 :(得分:0)

在className

之前修正了一个拼写错误 - {

如果 selected 为false,则可以返回空对象,否则返回预期值

示例:

export default function UiToggle(props) {
  const { leftLabel, rightLabel, selected, rightSideColor, leftSideColor } = props;

  return (
    <div className="lr-toggle-select" style={{ width: `${width}px` }} >
      <div className="lr-gray-background" />
      <div>
        {leftLabel}
      </div>
      <div className='lr-toggle right-toggle' style={ selected ? {backgroundColor: rightSideColor} : {} }}>
        {rightLabel}
      </div>
    </div>
  );
}