需要根据传递的道具添加不同的样式

时间:2019-05-06 15:44:50

标签: reactjs material-ui

我有一个选择组件,我需要根据传递的道具在选项中添加一些额外的填充。他的原因是,在某些情况下,我的图标绝对位于选择组件内部,因此在这种情况下需要在左侧留出空白

render()
const { classes, icon, selectWithIcon } = this.props;

return(
<Select
          value={this.state.value}
          onChange={this.handleChange}
          input={<FilledInput 
          name={this.props.label} 
          id={this.props.id} />}
        >
        {this.props.options && this.props.options.map(option => ( 
          <MenuItem value={option.value} >
            {<ListItemText className={classes.listItemText} primary={<Typography style={{ color: option.color, {selectWithIcon? marginLeft: '10px' : ''}}}>{option.text}</Typography>}/>}
          </MenuItem>
        ))}
        </Select>
)

如何添加条件以设置MenuItem内部的主要样式?上面的代码给我一个错误

1 个答案:

答案 0 :(得分:1)

这是正确的语法(您需要将条件放在marginLeft value 中,而不是样式对象中的键周围):

                <Typography
                  style={{
                    color: option.color,
                    marginLeft: selectWithIcon ? "10px" : ""
                  }}
                >
                  {option.text}
                </Typography>

这是一个完整的工作示例:

import React from "react";
import ReactDOM from "react-dom";

import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import ListItemText from "@material-ui/core/ListItemText";
import Typography from "@material-ui/core/Typography";

const MySelect = ({ selectWithIcon, options }) => {
  return (
    <Select value="1">
      {options.map(option => (
        <MenuItem value={option.value}>
          {
            <ListItemText
              primary={
                <Typography
                  style={{
                    color: option.color,
                    marginLeft: selectWithIcon ? "10px" : ""
                  }}
                >
                  {option.text}
                </Typography>
              }
            />
          }
        </MenuItem>
      ))}
    </Select>
  );
};
function App() {
  const options = [
    { text: "Item 1", value: 1, color: "blue" },
    { text: "Item 2", value: 2, color: "purple" }
  ];
  return (
    <div className="App">
      <MySelect options={options} selectWithIcon={true} />
      <br />
      <MySelect options={options} selectWithIcon={false} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit prop-based styling of MenuItem