React组件基础
React組件
1.創建組件
1)使用函數創建組件
函數名必須大寫、開頭必須有返回值、使用函數名作為標簽名
2)使用Class創建組件
大寫字母開頭、類組件要繼承React.Component父類,從而可以使用父類提供的方法或屬性、類組件必須使用render()方法、render()方法必須有返回值,表示該組件的結構
class MyClassComponent extends React.Component {render() {return <div>MyClassComponent</div>;} }ReactDOM.render(<MyClassComponent />, document.getElementById("root"));2.事件綁定
類組件:
class APP extends React.Component{handerClick() {console.log('111')}render() {return (<button onClick={this.handerClick}>按鈕</button>)} }函數組件:
function App() {function myClick(e) {e.preventDefault(); // 阻止默認行為console.log(e);}return (<div className="App"><a href="https://www.baidu.com/" onClick={myClick}>按鈕</a></div>); }3.有/無狀態組件(state 、setState )
狀態(state)即數據。
函數組件沒有自己的狀態,只負責數據展示。
類組件有自己的狀態,負責更新UI,讓頁面動起來。
2)setState()
class App extends React.Component {//初始化statestate = {count: 10,computed: 0,};render() {return (<div><buttononClick={() => {this.setState({computed: this.state.computed + 1,});}}>按鈕</button><span>無修改:{this.state.count}</span><span>修改:{this.state.computed}</span></div>);} }3)分離js
handerClick() {this.setState({computed: this.state.computed + 1,});}直接分離為函數會有this指向問題。行內函數為箭頭函數,箭頭函數沒有this,會指向父級(render)及組件實例。
解決this指向問題:
方法一:箭頭函數
class App extends React.Component {//初始化statestate = {computed: 0,};handerClick() {this.setState({computed: this.state.computed + 1,});}render() {return (<div><button onClick={() => this.handerClick()}>按鈕</button><span>修改:{this.state.computed}</span></div>);} }方法二:Bind()
利用es5中的bind方法,將事件中的this與組件實例綁定到一起。constructor中的this也指向實例,
綁定constructor中的this。
方 法三:class的實例方法(推薦)
函數直接使用箭頭函數
4.表單處理
1)受控組件(推薦):
class App extends React.Component {//初始化statestate = {computed: 0,};inputChange = (e) => {this.setState({computed: e.target.value,});};render() {return (<div><span>與input同步修改:{this.state.computed}</span><inputtype="text"value={this.state.computed}onChange={this.inputChange}></input></div>);} }2)非受控組件:
- 調用React.createRef() 方法創建一個ref對象
- 將創建好的ref對象添加到文本框中
- 通過ref對象獲取到文本框的值
總結
- 上一篇: 每个月要吃多少餐中餐,大概多少钱?
- 下一篇: 烧烤的发源地在哪里?