1 回答

TA貢獻1840條經驗 獲得超5個贊
你可能應該使用 jsx 而不是直接操作 dom:
function makeList(array) {
? ? return (
? ? ? ? <ul>
? ? ? ? ? ? (array.map((value, index) => (<li>{value}</li>)
? ? ? ? </ul>
? ? )
}
或者一個完整的、更優化的解決方案是創建一個Breakfast組件:
class Stuff extends Component {
? ? constructor(props) {
? ? ? ? super(props);
? ? ? ? this.source = {
? ? ? ? ? ? breakfast: [
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? id: 1,
? ? ? ? ? ? ? ? ? ? name: "eggs",
? ? ? ? ? ? ? ? ? ? img: image1,
? ? ? ? ? ? ? ? ? ? description: "Start a day with delicious and nutricious eggs!",
? ? ? ? ? ? ? ? ? ? ingridients: ['2 eggs', 'two slices of toast', 'bacon', 'butter']
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ]
? ? ? ? }
? ? }
? ? render() {
? ? ? ? return (
? ? ? ? ? ? <div>
? ? ? ? ? ? ? ? <Day source={this.source}></Day>
? ? ? ? ? ? </div>
? ? ? ? );
? ? }
}
class Day extends Component {
? ? render() {
? ? ? ? return (
? ? ? ? ? ? <div className="displayOne">
? ? ? ? ? ? ? ? {this.props.source.breakfast.map((breakfast) => <Breakfast breakfast={breakfast}/>)}
? ? ? ? ? ? </div>
? ? ? ? );
? ? }
}
function Breakfast({breakfast}) {
? ? return (
? ? ? ? <div className="displayOne">
? ? ? ? ? ? <img src={breakfast.img} alt="eggs"/>
? ? ? ? ? ? <h3>{breakfast.description}</h3>
? ? ? ? ? ? <ul>
? ? ? ? ? ? ? ? {breakfast.ingridients.map((ingridient) => <li>{ingridient}</li>)}
? ? ? ? ? ? </ul>
? ? ? ? </div>
? ? )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
添加回答
舉報