react_2

react_2

以下内容修改自下面链接:

http://www.runoob.com/react

函数组件

我们可以通过创建多个组件来合成一个组件,即把组件的不同功能点进行分离。

<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>

基于类的组件

  • 相比于函数式组件功能更强大。(下面会学到)它有state,以及不同的生命周期方法,可以让开发者能够在组件的不同阶段(挂载、更新、卸载),对组件做更多的控制。
    类组件可能是无状态组件,也可能是有状态组件。

props的意义与用法

props 在组件中扮演一个传递参数的角色

  • 在function里props,必须显式地传入我们的props。而在类里面,props不需要我们定义,是react里面就存在的一个东西,专门用来存放我们的要传递的参数的。

  • props可以传递多参数

<div id="example"></div>
<script type="text/babel">
class Welcome extends React.Component{
  render(){
    return (<div>my name is {this.props.name},{this.props.age}</div>);
  }
};
//const element必须在定义组件之后
const element = (
  <Welcome name='bty' age="12"/>
);
ReactDOM.render(
  element,
  document.getElementById('example')
);
</script>
  • props类似于const,不能修改的,只能通过组件调用时的属性定义。

比如下面的定义是错误的:

function Hello(props){
    props.name="lisi"
    return <div>hello world  +  {props.name} + {props.id}</div>
}

  • 类里面通过props传递参数要加this,并且,继承的时候还必须在constructor以及super里面显式地传递入props

  • 函数调用类

<div id="example"></div>
<script type="text/babel">
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>现在是 {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('example')
  );
}

setInterval(tick, 1000);
</script>
  • 类调用函数
<div id="example"></div>
<script type="text/babel">
function Myhi(props){
   return <h1>I‘m {props.name}</h1>
}
class Welcome extends React.Component{
  render(){
    return(
      <div>
        <p>start</p>
        <Myhi name="bty"/>
        <Myhi name="ssh"/>
        <Myhi name="mama"/>
      </div>)    
  }
};
ReactDOM.render(
  <Welcome/>,
  document.getElementById('example')
);
</script>

课间题

函数改类;类改函数

1,请写一个类,通过段落(p)在页面上输出“春眠不觉晓”

2,写一个类,通过标题(h2)在页面上输出某个内容,这个内容需要通过参量传递进去

3, “类调用函数”这部分的例子,请把其中的类改为函数,函数改为类,然后相互调用,并保持输出结果不变

state

  • state的作用

state是React中组件的一个对象.React把用户界面当做是状态机,想象它有不同的状态然后渲染这些状态,可以轻松让用户界面与数据保持一致.
React中,更新组件的state,会导致重新渲染用户界面(不要操作DOM).简单来说,就是用户界面会随着state变化而变化.

  • state与props的区别:

props是一个父组件传递给子组件的数据流,可以一直的被传递到子孙组件中。然而 state代表的是子组件自身的内部状态;
props的值不可改变,state可以被改变。

1.state是自己的私有状态,state是可以改变的
2.props一般是父组件或者是通过状态机Redux传过来的状态,props我们只会去拿来用,不会去改变它

  • 下面的例子里数值并不能发生变化
<div id="example"></div>
<script type="text/babel">
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')
);
</script>
  • 在不进行多次函数运行的情况下改变数值(改变组件的状态):

  • setState可以用来进行批量更新

<div id="example"></div>
<script type="text/babel">
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

//componentDidMount总是会在第一次输出后执行
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

//componentWillUnmount总是会在输出被移除后执行
  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')
);
</script>

实例解析:

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

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

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

代码执行顺序:

1,当 被传递给 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() 这个钩子函数,定时器也就会被清除。

课间题

1,请写一个类组件,输出“xx今年yy岁了!”,注意xx与yy是一个你自己定义的量,这两个量的定义通过类的内部赋值完成

2,请写一个类组件,输出“xx今年yy岁了!”,注意xx与yy是一个你自己定义的量,这两个量的定义通过调用类组件是通过参数传递进去

3,参考上面的例子,写一个类组件,输出“xx今年yy岁了!”,但是让这个输出的岁数每秒会自动增加1岁。

React处理事件

  • React事件处理VS原生Dom事件处理

原生DOM事件写法:

<input type="button" onclick="fn()">

React中写法:

<input type="button" onClick={fn}>
  • 回调函数及其应用
<div id="example"></div>
<script type="text/babel">
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // 这边绑定是必要的,这样 `this` 才能在回调函数中使用
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

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

其他三种实现方式

  render() {
    return (
      <button onClick={this.handleClick.bind(this)}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
  handleClick = () => {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }
  render() {
    return (
      <button onClick={(e) => this.handleClick(e)}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }

向事件处理程序传递参数

  • 通常我们会为事件处理程序传递额外的参数。例如,若是 id 是你要删除那一行的 id,以下两种方式都可以向事件处理程序传递参数:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
<div id="example"></div>
<script type="text/babel">
class Popper extends React.Component{
    constructor(){
        super();
        this.state = {name:'Hello world!'};
    }
    
    preventPop(name, e){    //事件对象e要放在最后
        e.preventDefault();
        alert(name);
    }
    
    render(){
        return (
            <div>
                <p>hello</p>
                {/* 通过 bind() 方法传递参数。 */}
                <a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a>
            </div>
        );
    }
}

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

课间题

1,请复习《web开发之javascript_1》写一个按钮,点击后输出“春眠不觉晓”(不用react,直接用js)

2,请用react类组件实现一个按钮,通过函数回调的方式,实现每次点击岁数增加1

在这里插入图片描述

3,请用剩下的三种方法实现上题的效果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值