React的介绍和使用安装

React

声明式

React 使创建交互式 UI 变得轻而易举。为你应用的每一个状态设计简洁的视图,当数据改变时 React 能有效地更新并正确地渲染组件。

组件化

创建拥有各自状态的组件,再由这些组件构成更加复杂的 UI。
组件逻辑使用 JavaScript 编写而非模版,因此你可以轻松地在应用中传递数据,并使得状态与 DOM 分离。

class HelloMessage extends React.Component {
    
    
  render() {
    
    
    return (
      <div>
        Hello {
    
    this.props.name}
      </div>
    );
  }
}

ReactDOM.render(
  <HelloMessage name="Taylor" />,
  document.getElementById('hello-example')
);

React 组件使用一个名为 render() 的方法,接收输入的数据并返回需要展示的内容。在示例中这种类似 XML 的写法被称为 JSX。被传入的数据可在组件中通过 this.props 在 render() 访问.

除了使用外部数据(通过 this.props 访问)以外,组件还可以维护其内部的状态数据(通过 this.state 访问)。当组件的状态数据改变时,组件会再次调用 render() 方法重新渲染对应的标记。

class Timer extends React.Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.state = {
    
     seconds: 0 };
  }

  tick() {
    
    
    this.setState(state => ({
    
    
      seconds: state.seconds + 1
    }));
  }

  componentDidMount() {
    
    
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    
    
    clearInterval(this.interval);
  }

  render() {
    
    
    return (
      <div>
        Seconds: {
    
    this.state.seconds}
      </div>
    );
  }
}

ReactDOM.render(
  <Timer />,
  document.getElementById('timer-example')
);

基于自动化的集成环境模式 - create-react-app - 脚手架

安装与使用

通过 npm、yarn、npx 都可以

安装

npm
npm i -g create-react-app
yarn
yarn global add create-react-app

使用

安装完成以后,即可使用 create-react-app 命令

create-react-app <项目名称>

猜你喜欢

转载自blog.csdn.net/weixin_54645137/article/details/114040294