React

React

MV*

Model: state.Simple JS objects

View: widgets on the page

Controller: code that acts on the model

<div id="example"></div>
<script type="text/babel">
  ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('example')
  );
</script>

 

JSX

 

var myStyle = {
    fontSize: 100,
    color: '#FF0000'
};
ReactDOM.render(
    <h1 style = {myStyle}>菜鸟教程</h1>,
    document.getElementById('example')
);

 

Component

复制代码
复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>菜鸟教程 React 实例</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>

<div id="example"></div>
<script type="text/babel">

//我们用函数定义了一个组件 class Welcome extends React.Component { render() { return <h1>Hello World!</h1>; } } //element是自定义的 const element = <Welcome />; ReactDOM.render( element, document.getElementById('example') ); </script> </body> </html>
复制代码
复制代码

如果我们需要向组建传递参数,可以使用this.prop对象,实例如下:

复制代码
function HelloMessage(props) {
    return <h1>Hello {props.name}!</h1>;
}
 
const element = <HelloMessage name="Runoob"/>;
 
ReactDOM.render(
    element,
    document.getElementById('example')
);
复制代码

我们可以用几个小组件变成一个大组件:

复制代码
<html>
<head>
<meta charset="UTF-8" />
<title>菜鸟教程 React 实例</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>

<div id="example"></div>
<script type="text/babel">
function Name(props) {
    return <h1>网站名称:{props.name}</h1>;
}
function Url(props) {
    return <h1>网站地址:{props.url}</h1>;
}
function Nickname(props) {
    return <h1>网站小名:{props.nickname}</h1>;
}
function App() {
    return (
    <div>
        <Name name="菜鸟教程" />
        <Url url="http://www.runoob.com" />
        <Nickname nickname="Runoob" />
    </div>
    );
}

ReactDOM.render(
     <App />,
    document.getElementById('example')
);
</script>

</body>
</html>
复制代码

 

React State(状态)

React 把组件看成是一个状态机(State Machines)。通过与用户的交互,实现不同状态,然后渲染 UI,让用户界面和数据保持一致。

React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面(不要操作 DOM)。

复制代码
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
 
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>现在是 {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
 
ReactDOM.render(
  <Clock />,
  document.getElementById('example')
);
复制代码

我们将使Clock设置自己的计时器并每秒更新一次。

复制代码
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
 
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }
 
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
 
  tick() {
    this.setState({
      date: new Date()
    });
  }
 
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>现在是 {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
 
ReactDOM.render(
  <Clock />,
  document.getElementById('example')
);
复制代码

实例解析:

componentDidMount() 与 componentWillUnmount() 方法被称作生命周期钩子。

在组件输出到 DOM 后会执行 componentDidMount() 钩子,我们就可以在这个钩子上设置一个定时器。

this.timerID 为定时器的 ID,我们可以在 componentWillUnmount() 钩子中卸载定时器。

代码执行顺序:

  1. 当 <Clock /> 被传递给 ReactDOM.render() 时,React 调用 Clock 组件的构造函数。 由于 Clock 需要显示当前时间,所以使用包含当前时间的对象来初始化 this.state 。 我们稍后会更新此状态。

  2. React 然后调用 Clock 组件的 render() 方法。这是 React 了解屏幕上应该显示什么内容,然后 React 更新 DOM 以匹配 Clock 的渲染输出。

  3. 当 Clock 的输出插入到 DOM 中时,React 调用 componentDidMount() 生命周期钩子。 在其中,Clock 组件要求浏览器设置一个定时器,每秒钟调用一次 tick()

  4. 浏览器每秒钟调用 tick() 方法。 在其中,Clock 组件通过使用包含当前时间的对象调用 setState() 来调度UI更新。 通过调用 setState() ,React 知道状态已经改变,并再次调用 render() 方法来确定屏幕上应当显示什么。 这一次,render() 方法中的 this.state.date 将不同,所以渲染输出将包含更新的时间,并相应地更新 DOM。

  5. 一旦 Clock 组件被从 DOM 中移除,React 会调用 componentWillUnmount() 这个钩子函数,定时器也就会被清除。

 

React Props(属性)

state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。

复制代码
function HelloMessage(props) {
    return <h1>Hello {props.name}!</h1>;
}
 
const element = <HelloMessage name="Runoob"/>;
 
ReactDOM.render(
    element,
    document.getElementById('example')
);
复制代码

实例中 name 属性通过 props.name 来获取。

你可以通过组件类的 defaultProps 属性为 props 设置默认值,

复制代码
class HelloMessage extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}
 
HelloMessage.defaultProps = {
  name: 'Runoob'
};
 
const element = <HelloMessage/>;
 
ReactDOM.render(
  element,
  document.getElementById('example')
);
复制代码

React action

React 元素的事件处理和 DOM 元素类似。但是有一点语法上的不同:

  • React 事件绑定属性的命名采用驼峰式写法,而不是小写。
  • 如果采用 JSX 的语法你需要传入一个函数作为事件处理函数,而不是一个字符串(DOM 元素的写法)

HTML 通常写法是:

<button onclick="activateLasers()">
  激活按钮
</button>

React 中写法为:

<button onClick={activateLasers}>
  激活按钮
</button>

React render

在 React 中,你可以创建不同的组件来封装各种你需要的行为。然后还可以根据应用的状态变化只渲染其中的一部分。

React 中的条件渲染和 JavaScript 中的一致,使用 JavaScript 操作符 if 或条件运算符来创建表示当前状态的元素,然后让 React 根据它们来更新 UI。

复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 实例</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="example"></div>

<script type="text/babel">
function UserGreeting(props) {
  return <h1>欢迎回来!</h1>;
}

function GuestGreeting(props) {
  return <h1>请先注册。</h1>;
}

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={false} />,
  document.getElementById('example')
);
</script>

</body>
</html>
复制代码
复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 实例</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="example"></div>

<script type="text/babel">
function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          您有 {unreadMessages.length} 条未读信息。
        </h2>
      }
    </div>
  );
}

const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
  <Mailbox unreadMessages={messages} />,
  document.getElementById('example')
);
</script>

</body>
</html>
复制代码

Code examples

 

 

 

 

复制代码
import './App.css';
import React from 'react';

class App extends React.Component{
    state = {
        name:'character design',
        stats: {
            Charisma:1,
            Prowess:0,
            Agility:0,
            Strength:0,
        }
    }
    notifyStatChange(stat,value) {
        let stats = {};
        Object.assign(stats,this.state.stats);
        stats[stat]+=value;
        this.setState({stats: stats})
    }
    constructor() {
        super();
        this.notifyStatChange=
            this.notifyStatChange.bind(this);
    }
    render() {
        const {stats}=this.state
        return(
            <StatEditor stats = {stats}
                        mine = "Charisma" rtl="false"
            notifyStatChange={this.notifyStatChange} />

        )
    }
}
// class StatEditor extends React.Component{
//     canDecrease(){
//         const stats = this.props.stats;
//         const mine = this.props.mine;
//         const val = stats[mine];
//         return val > 0;
//     }
//     canIncrease(){
//         const stats = this.props.stats;
//         const mine = this.props.mine;
//         const val = stats[mine];
//         return val <100;
//     }
//     decrease(){
//         if(!this.canDecrease()){return ;}
//         this.props.notifyStatChange(this.props.mine,-1)
//     }
//     increase(){
//         if(!this.canIncrease()){return ;}
//         this.props.notifyStatChange(this.props.mine,+1)
//     }
//     value(){return this.props.stats[this.props.mine]}
//     render() {
//         return(
//             <div className="character design" id={this.props.mine + "Editor"}>
//                 <button className="adjuster"
//                     disabled={!this.canDecrease()}
//                     onClick={this.decrease}>-
//                 </button>
//                 <input disabled value={this.value()}/>
//                 <button className="adjuster"
//                         disabled={!this.canIncrease()}
//                         onClick={this.increase}>+
//                 </button>
//                 <span className="peText">&nbsp;{this.props.mine}</span>
//             </div>
//         )
//     }
// }
class StatEditor extends React.Component {
    value() {
        return this.props.stats[this.props.mine];
    }
    constructor() {
        super();
        this.canDecrease = () => {
            const stats = this.props.stats;
            const mine = this.props.mine;
            const val = stats[mine];
            return val > 0;
        };
        this.canIncrease = () => {
            const stats = this.props.stats;
            const mine = this.props.mine;
            const val = stats[mine];
            return val < 10;
        };
        this.decrease = () => {
            console.log("hello");
            if (!this.canDecrease()) {
                return;
            }
            this.props.notifyStatChange(this.props.mine, -1);
        };
        this.increase = () => {
            if (!this.canIncrease()) {
                return;
            }
            this.props.notifyStatChange(this.props.mine, +1);
        };
    }
    render() {
        return (
            <div className="character design" id={this.props.mine + "Editor"}>
                <button
                    className="adjuster"
                    disabled={!this.canDecrease()}
                    onClick={this.decrease}
                >
                    -
                </button>
                <input disabled value={this.value()} />
                <button
                    className="adjuster"
                    disabled={!this.canIncrease()}
                    onClick={this.increase}
                >
                    +
                </button>
                <span className="peText">&nbsp;{this.props.mine}</span>
            </div>
        );
    }
}
export default App;
复制代码

 

posted @   君逸堂  阅读(69)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示