
安装之前要先查看自己是否安装了 node.js
react 脚手架 npm i -g create-react-app
安装之后安装一下依赖包
中index.js中就是他的入口文件 App.js就是我们写代码的地方(你也可以写其他地方)
index中我们可以看到
import React from "react";
import "./App.css";
class App extends React.Component {
constructor(props) {
super(props);
// 定义数据
this.state={
name:'张三'
}
}
render() {
return (
// 使用
<div> {this.state.name} </div>
)
}
}
export default App;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fruits: ["香蕉", "雪梨", "苹果"],
};
}
handClick(name){
console.log(name);
}
render() {
return (
<div>
<ul>
{
this.state.fruits.map((item,index)=>{
return <li key={index} onClick={this.handClick.bind(this,item)}>{item}</li>
})
}
</ul>
</div>
)
}
}
// 第一种 this.handClick.bind(this) 绑定this
<h2 onClick={this.handClick.bind(this)}>第一种this</h2>
// 第二 this.handClick = this.handClick.bind(this)
constructor(props) {
this.handClick = this.handClick.bind(this)
}
<h2 onClick={this.handClick}>第二种this 配合constructor使用</h2>
// 第三 {()=>{this.handClick()}}
<h2 onClick={()=>{this.handClick()}}>第三种this</h2>
计数器案例
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
count:0
};
}
render(){
return (
<div>
<h2>当前计数:{this.state.count} </h2>
<button onClick={this.add.bind(this)}>count++</button>
<button onClick={this.reduce.bind(this)}>count--</button>
<button onClick={this.add.bind(this,10)}>count+10</button>
</div>
)
}
add(num){
if(typeof(num) === 'number'){
this.setState({
count:this.state.count+10
})
return
}
this.setState({
count:this.state.count+1
})
}
reduce(){
this.setState({
count:this.state.count-1
})
}
}
ReactDOM.render(<App/>,document.querySelector('#app'))
// 子组件
class ChildCom extends React.Component {
constructor(props){
super(props)
this.state={
name:'我是子组件传递的数据'
}
}
handClick(){
this.props.getMsg(this.state.name)
}
render(){
return(
<div>
<p>父组件数据:{this.props.msg}</p>
<button onClick={this.handClick.bind(this)}>点击给父组件传数据</button>
</div>
)
}
}
// 父组件
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
msg:'我是父组件传给子组件的数据',
childData:''
};
}
getChildMsg(msg){
this.setState({
childData:msg
})
}
render() {
return (
<div>
<h1>子组件</h1>
{/* 父传子 */}
<ChildCom msg={this.state.msg} getMsg={this.getChildMsg.bind(this)} />
<h1> 父组件 </h1>
<p>传的数据:{ this.state.childData } </p>
</div>
)
}
}