1. 程式人生 > 其它 >好客租房41-react元件基礎綜合案例-渲染列表資料

好客租房41-react元件基礎綜合案例-渲染列表資料

1渲染列表

在state定義資料

進行資料渲染

//匯入react
import React from 'react'
import ReactDOM from 'react-dom'
//匯入元件
// 約定1:類元件必須以大寫字母開頭
// 約定2:類元件應該繼承react.component父類 從中可以使用父類的方法和屬性
// 約定3:元件必須提供render方法
// 約定4:render方法必須有返回值
 
class HelloWorld extends React.Component {
    //初始化狀態
    state={
        comments:[{
            id:1,name:"geyao",content:"哈哈"
        },{
            id:2,name:"fangfang",content:"哈哈"
        },{
            id:3,name:"geyao",content:"哈哈"
        }]
    }
    render() {
        return (
            <div className="app">
                <div>
                    <input
                        className="user"
                        type="text"
                        placeholder="請輸入評論人"
                    />
                    <br />
                    <textarea
                        className="content"
                        cols="30"
                        rows="10"
                        placeholder="請輸入評論列表"
                    ></textarea>
                    <br />
                    <button>發表評論</button>
                </div>
                <div className="no-comment">暫無評論,快去評論吧~</div>
                <ul>
                    {/* <li>
                        <h3>評論人:jack</h3>
                        <h3>評論內容:沙發</h3>
                    </li> */}
                    {this.state.comments.map(item=>(
                        <li key={item.key}>
                        <h3>評論人:{item.name}</h3>
                        <p>評論內容:{item.content}</p>
                    </li>
                    )
                      
                        
                    )}
                </ul>
            </div>
        )
    }
}
 
ReactDOM.render(<HelloWorld />, document.getElementById('root'))
執行結果