React 第一章

118 阅读1分钟

快速创建一个新的单页应用

条件:Node >= 8.10 ,npm >= 5.6

// 全局安装 create-react-app
node -v
npm -v
nrm ls // 切换镜像
nrm use taobao //用淘宝镜像
npm install -g create-react-app
sudo npm install -g create-react-app//苹果安装
npx create-react-app my-app  //第一种
create-react-app my-app // 第二种
cd my-app
npm start

会生成一个网页,localhost:3000的地址

JSX

JSX是一个JavaScript的语法扩展。

  • JSX中嵌入表达式
const element = <h1>Hello,{name}</h1>

ReactDom.render(element,document.getElementById('root'))
  • JSX特定属性

可以使用引号,将属性值指定为字符串字面量

const element = <div tabIndex = '0'></div>

也可以使用大括号,在属性值中插入一个JavaScript表达式

const element = <img src={user.avatarUrl}></img>
  • JSX指定子元素
const element = (
  <div>
   <h1>Hello</h1>
  </div>
)
  • JSX 防止注入攻击

React DOM在渲染所有输入内容之前,默认会进行转义,有效防止XSS攻击

组件

最简单的组件是一个JS函数

function test(props){
    return <h1>Hello,{props.name}</h1>
}

ES6的 class定义组件

class Test extends React.Component {
   render(){
     return <h1>Hello,{this.props.name}</h1>
   }
}

React 框架渲染组件的

const element = <Test name = "Tom" />

react事件处理

使用JSX语法时需要传入一个函数作为事件处理函数,不是一个字符串

<button onClick={clickGetData}></button>

在组件中添加render()函数时,事件的绑定要添加this

class Test extends React.Component {
    handleClick =()=>{
      console.log('xxxx')
    }
    render(){
      return (
        <button onClick={this.handleClick}>Click me</button>
      )
    }
}