1.コンポーネント
import React from ' react ' ; import ReactDOM from ' react-dom ' ; import ' ./index.css ' ; // 機能コンポーネントの戻り 関数Hello(props){ let titleName = <p>これはHelloサブタイトルです</ p > return ( <div> <h1>今日の天気:{props.weather} </ h1> {titleName} </ div> ) // コンポーネントで有効な仮想jsx dom要素を返す必要があります} // クラスコンポーネントクラスHi React.Component { render(){ return ( <div> <h1>今日の天気:{ これ .props.weather} </ h1> </ div> ) } } ReactDOM.render( <div> <Hello weather = " 出太阳" /> <Hi weather = " 出太阳" /> </ div> 、 ドキュメント。 getElementById(' root ' ) );
第二に、コンポーネントの状態
import React from ' react ' ; import ReactDOM from ' react-dom ' ; import ' ./index.css ' ; // この種類の書き込みコンポーネントは自動的に更新できません class Hello extends React.Component { // ステートプライベート コンストラクター( プロパティ ) { super(props)this .state = { time:new Date()。toLocaleTimeString() } } // View render(){ // eslintなしでエラーを報告 // // eslint-disable-next-line this.state.time = new Date()。toLocaleTimeString() return ( <div> <h1>現在の時刻:{ this .state.time} </ h1> </ div> ) } } ReactDOM.render( <div> < Hello /> </ div> 、 document.getElementById(' root ' ) ); setInterval(() => { // 同じコンポーネントの繰り返しレンダリングは繰り返されないため、 ReactDOM.render( < div> <Hello /> </ div>、 document.getElementById( 'root') ); }、1000)
'react'からReactをインポートします。 ReactDOMを 'react-dom' からインポートします。 import './index.css' ; クラスHello extends React.Component { // 状态-私有 constructor(props){ super(props) this .state = { time:new Date()。toLocaleTimeString() } console.log(this .state.time) } // 视图 render(){ return ( <div> <h1> 当前時間间:{ this .state.time} </ h1> </ div> ) } // 生命周期 componentDidMount(){ setInterval(()=> { // setState() this.setState({time:new Date()。toLocaleTimeString()}) }、1000 ) } } ReactDOM.render( <div> <Hello /> </ div>、 document.getElementById( 'root' ) )
3、クリックイベント
'react'からReactをインポートします。 ReactDOMを 'react-dom' からインポートします。 import './index.css' ; クラスHello extends React.Component { constructor(props){ super(props) this .state = { c1: 'active' 、 c2: 'content' } // 改变show1的this指向 this .show1 = this .show1.bind(this ) } render(){ return ( <div> <button onClick = { this .show}>不传参写法</ button> <button onClick = {()=>.show( '1')}> 1つ</ button> <button onClick = {()=> this .show( '2')}> 2つ</ button> { / * 今回はshow1がボタンを指す* / } を指すように変更します<button data-index = "1" onClick = { this .show1}> One </ button> <button data-index = "2" onClick = { this .show1}> Two </ button> <div className = { this .state.c1}>コンテンツ1 </ div> <div className = { this .state.c2}>コンテンツ2 </ div> </ div> ) } show(arg){ console 。log(arg) if(arg === '1' c1: ){ this .setState({'active' 、 c2: 'content' }) } else { this .setState({ c2: 'active' 、 c1: 'content' }) } } show1(e){ console.log(e.target.dataset.index ) let arg = e.target.dataset.index if(arg === '1' ){ this .setState({ c1: 'active' 、 c2: 'content' }) } else { this 。setState({ c2: 'active' 、 c1: 'content' }) } } } ReactDOM.render( <div> <Hello /> </ div>、 document.getElementById( 'root' ) )