【问题标题】:Dynamically change a mapped list style property inside a react component动态更改反应组件内的映射列表样式属性
【发布时间】:2018-04-04 12:54:27
【问题描述】:

我有一个 defautProps 数组,其中包含我通过映射和过滤在无序列表中显示的所有命名颜色。我已经显示了每种颜色名称,但我想使用该命名颜色作为内联样式标签的背景颜色。下面包括不成功的内联样式代码。感谢您的任何建议。

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

    this.state = {
      filterBy: ''
    };
  }

  filterColors = () => {
    const clr = document.getElementById('filter').value;
    this.setState({ filterBy: clr})
  }

  getColor = (idx) => {
    return this.props.allColors[idx]
  }

  render () {
    const arr = this.props.allColors;
    const filterBy = clr => clr.includes(this.state.filterBy);
    const backgroundColor = this.getColor(16)


    const style = {
      width: '20px',
      height: '20px',
      backgroundColor: this.getColor({idx})
    }

    const colors = arr.filter(filterBy).map((color, idx) =>
    (
        <li key={idx}>{color} <div style={style} id={idx} /> </li>
    ));

    return (
      <div>
        <h3>Named Colors</h3>
        <ul>
          {colors}
        </ul>
        <input type="text" placeholder="Filter by" id="filter" onChange={this.filterColors}></input>
      </div>
    );
  }
}

JSexp.defaultProps = {
  allColors: ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond",
    "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate",
    "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod",
    "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange",
    "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey",
    "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue",
    "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod",
    "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki",
    "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan",
    "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon",
    "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow",
    "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid",
    "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise",
    "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy",
    "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen",
    "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue",
    "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen",
    "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen",
    "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke",
    "Yellow", "YellowGreen"]
};

【问题讨论】:

  • 你使用的是什么版本的 react?我在这里遇到了您的代码的一些问题。上面的 sn-p 是否在本地为您运行?你能在codesandbox.io中重新创建吗?
  • 我确实知道我做错了什么。你可以在这里查看工作代码:3l7q41026.codesandbox.io
  • 很棒的伙伴。我明白了……

标签: css reactjs dynamic jsx


【解决方案1】:

如果我正确理解您的问题,您可以在进行数组映射时指定 div 的 backgroundColor。

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

    this.state = {
      filterBy: ''
    };
  }

  filterColors = (e) => {
    this.setState({ filterBy: e.target.value})
  }


  render () {
    const arr = this.props.allColors;
    const filterBy = clr => clr.includes(this.state.filterBy);

    const colors = arr.filter(filterBy).map((color, idx) =>
        <li key={idx}>
          {color}
          <div style={{width: 20, height: 20, backgroundColor: color}}>
          </div>
        </li>
    );

    return (
      <div>
        <input type="text" placeholder="Filter by" id="filter" onChange={this.filterColors}></input>
 
        <h3>Named Colors</h3>
        <ul>
          {colors}
        </ul>

      </div>
    );
  }
}


JSexp.defaultProps = {
  allColors: ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond",
    "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate",
    "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod",
    "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange",
    "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey",
    "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue",
    "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod",
    "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki",
    "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan",
    "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon",
    "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow",
    "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid",
    "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise",
    "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy",
    "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen",
    "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue",
    "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen",
    "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen",
    "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke",
    "Yellow", "YellowGreen"]
};

ReactDOM.render(<JSexp />, document.getElementById('root'))
<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>
<div id="root"></div>

【讨论】:

    【解决方案2】:

    这里

    const style = {
      width: '20px',
      height: '20px',
      backgroundColor: this.getColor({idx})
    }
    

    您似乎缺少 {idx} 值。

    试试

    const colors = arr.filter(filterBy).map((color, idx) => {
        const style = {
          width: '20px',
          height: '20px',
          backgroundColor: this.getColor({idx})
        }
    
        return <li key={idx}>{color} <div style={style} id={idx} /> </li>
    )});
    

    【讨论】:

      【解决方案3】:

      嗯,经过一夜好眠后,我确实找出了问题所在。这实际上比我想象的要容易得多:

      class NamedColors extends React.Component {
        constructor(props) {
          super(props);
      
          this.state = {
            filterBy: ''
          };
        }
      
        filterColors = () => {
          const clr = document.getElementById('filter').value;
          this.setState({ filterBy: clr })
        }
      
        render() {
      
          const itemStyle = {
            fontSize: '.85rem',
            padding: '5px'
          }
      
          const contentDisplay = {
            display: 'flex',
            flexDirection: 'row',
            flexWrap: 'wrap',
            padding: '5px'
          }
      
          const contentHeader = {
            display: 'flex',
            alignItems: 'baseline'
          }
      
          const arr = this.props.allColors;
      
          const filterBy = (strToFilter) => {
            return strToFilter.includes(this.state.filterBy)
          };
      
          const colors = arr.filter(filterBy).map((color, idx) =>
            (
              <div key={idx + 10}>
                <div key={idx} style={itemStyle}>
                  {color}
                  <div style={
                    {
                      backgroundColor: color,
                      width: '150px',
                      height: '32.5px',
                      border: 'solid',
                      borderWidth: '1px'
                    }
                  } />
                </div>
              </div>
            ));
      
          return (
            <div>
              <div style={contentHeader}>
                <h3>Named Colors</h3>&nbsp;&nbsp;&nbsp;
                <input type="text" placeholder="Filter by" id="filter" onChange={this.filterColors}></input>
              </div>
              <div style={contentDisplay}>
                {colors}
              </div>
            </div>
          );
        }
      }
      
      NamedColors.defaultProps = {
        allColors: ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond",
          "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate",
          "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod",
          "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange",
          "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey",
          "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue",
          "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod",
          "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki",
          "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan",
          "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon",
          "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow",
          "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid",
          "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise",
          "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy",
          "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen",
          "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue",
          "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen",
          "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen",
          "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke",
          "Yellow", "YellowGreen"]
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-31
        • 2020-11-03
        • 1970-01-01
        • 2012-05-07
        • 2023-01-16
        • 1970-01-01
        相关资源
        最近更新 更多