react 繫結資料 繫結屬性 引入圖片 迴圈資料
阿新 • • 發佈:2018-11-22
繫結資料:
需要注意在react 元件中沒有this指向物件,所以我們必須在constructor 建構函式中進行super(props);
import React from 'react'; class Home extends React.Component{ constructor (props) { super(props); this.state = { mes: "我是一個home元件", title: "我是home的標題" } } hanlederClick(e) { alert(e); } render() { return ( <div> <h1 onClick={this.hanlederClick.bind(this)}> {this.state.title}</h1> <p> {this.state.mes} </p> </div> ); } } export default Home;
繫結屬性
class 是js中的關鍵字 在jsx語法中繫結class類屬性用className代替;
for 中用htmlFor代替 <label for = 'name'> </label> ===> <label htmlFor = ''> </label>
style標籤 繫結的兩種方式:
1): 直接{{}} <h5 style={{"color": "red","font-size": "15px"}}>;
2): this.state.style = {}
圖片的引用:
兩種方式: require 或者 import
import Hyk from '../assets/imges/hyk.jpg' 元件引用;
requrie es5 一種方法;
陣列迴圈:
import React from 'react'; import Hyk from '../assets/imges/hyk.jpg' class Image extends React.Component { constructor (props){ super(props); this.state = { students: [{ name: "甘雪", age: 12, sex: 1 },{ name: "楊浩威", age: 23, sex: 2 }] } }; render() { let studentResult = this.state.students.map((value,index)=>{ value['sex'] = value['sex'] == 1? "女" : "男"; return <tr> <td>{index}</td> <td>{value['name']}</td> <td>{value['age']}</td> <td>{value['sex']}</td> </tr> }) return ( <div> <div style={{width:"200px"}}> <h1>import</h1> <img width="200px" src={Hyk}/> </div> <div style={{width:"200px"}}> <h1>require</h1> <img width="200px" src={require('../assets/imges/hyk.jpg')}/> </div> <hr/> <table width="300" border="1" cellspacing="0" cellpadding="0"> <tr> <th>序號</th> <th>姓名</th> <th>年齡</th> <th>性別</th> </tr> {studentResult} </table> </div> ) } } export default Image;
App.js
import React, { Component } from 'react';
import './assets/css/App.css';
import Home from './components/Home';
import Imge from './components/Image';
class App extends Component {
render() {
return (
<div className="App">
<Home/>
<Imge/>
<header className="App-header">
hello React!!
</header>
</div>
);
}
}
export default App;