在渲染中显示数组映射

时间:2018-05-24 13:35:02

标签: reactjs

尝试在我的组件中显示图像数组,我只得到一个空div:

class StarRating extends React.Component {
    render() {
        const { rating } = this.props;

        const ratings = [...Array(5)].map((item, i) => {
            let src = rating < i ? "star-filled" : "star-unfilled";
            <img
                style={styles.image}
                src={require(`../../../../assets/${src}.png`)}
            />;
        });

        return <div style={styles.container}>{ratings}</div>;
    }
}

如何显示图像?

2 个答案:

答案 0 :(得分:1)

您错过了评级声明中的返回。如果您在{}中使用map,则需要说明退货。

const ratings = [...Array(5)].map((item, i) => {
            let src = rating < i ? "star-filled" : "star-unfilled";
            return <img // add return
                style={styles.image}
                src={require(`../../../../assets/${src}.png`)}
            />;
        });

修改的。添加选项而不返回:

const ratings = [...Array(5)].map((item, i) => 
            <img
                style={styles.image}
                src={require(`../../../../assets/${rating < i ? "star-filled" : "star-unfilled"}.png`)}
            />
        );

答案 1 :(得分:0)

你忘了回到地图内。

class StarRating extends React.Component {
  render() {
    const { rating } = this.props;

    const ratings = [...Array(5)].map((item, i) => {
      let src = rating < i ? 'star-filled' : 'star-unfilled';
      return (
        <img
          style={styles.image}
          src={require(`../../../../assets/${src}.png`)}
        />
      );
    });

    return <div style={styles.container}>{ratings}</div>;
  }
}