JavaScript中React面向组件编程怎么使用

其他教程   发布日期:2024年10月31日   浏览次数:247

这篇文章主要介绍“JavaScript中React面向组件编程怎么使用”,在日常操作中,相信很多人在JavaScript中React面向组件编程怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”JavaScript中React面向组件编程怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

前言:

  • React组件中默认封装了很多属性,有的是提供给开发者操作的,其中有三个属性非常重要:state、props、refs。通过这三大核心属性的使用,我们能够实现对组件的状态进行更新。

一,组件的基本理解和使用

1. 函数组件

  1. <script type="text/babel">
  2. function MyComponent() {
  3. return <h3>我是函数定义的组件(适用于简单组件的定义)</h3>
  4. }
  5. ReactDOM.render(<MyComponent />, document.getElementById('test'))
  6. </script>

函数组件的渲染过程

  1. 1.React解析了组件标签,找到了对应的组件
  2. 2.发现这个组件是一个函数定义的,随后调用该函数,生成一个虚拟dom
  3. 3.最后将虚拟dom转化成为真实dom,呈现在页面中

2. 类式组件

  1. <script type="text/babel">
  2. class MyComponent extends React.Component {
  3. render() {
  4. return <h3>我是类定义的组件适用于复杂数据类型</h3>
  5. }
  6. }
  7. ReactDOM.render(<MyComponent />, document.getElementById('test'))
  8. </script>

类式组件的渲染过程

  1. 1.React解析了组件标签,找到了对应的组件
  2. 2.发现这个组件是一个类定义的,随后new出来一个实例对象,并通过该实例调用原型上的render方法
  3. 3.render()返回的内容生成一个虚拟dom
  4. 4.最后将虚拟dom转化成为真实dom,呈现在页面中

3.组件的注意事项

  1. 组件名必须首字母大写
  2. 虚拟DOM元素只能有一个根元素
  3. 虚拟DOM元素必须有结束标签

二,组件的三大核心属性

1.state

    1. state
    是一个对象,它包含组件的数据状态,当状态变化时,会触发视图的更新。你可以理解它的作用跟
    1. Vue
    中的
    1. data
    对象类似。
  1. <script type="text/babel">
  2. class Weather extends React.Component {
  3. constructor() {
  4. super()
  5. this.state = {
  6. isHot: false,
  7. wind: '微风'
  8. }
  9. this.chang = this.chang.bind(this)
  10. }
  11. render() {
  12. let { isHot, wind } = this.state
  13. return <h3 onClick={this.chang}>今天的天气很 {isHot ? "炎热" : "凉爽"},{wind}</h3>
  14. }hang() {
  15. console.log(this)
  16. this.setState({
  17. isHot: !this.state.isHot
  18. })
  19. }
  20. }
  21. ReactDOM.render(<Weather />, document.getElementById('test'))
  22. </script>

1. 注意事项

  1. 1.组件中render方法中的this为组件实例对象
  2. 2.组件自定义的方法中thisundefined,如何解决?
  3. 1.强制绑定this: 通过函数对象的bind()
  4. 2.箭头函数
  5. 3.状态数据,不能直接修改或更

2.简写方式

  1. <script type="text/babel">
  2. class Weather extends React.Component {
  3. state = {
  4. isHot: false,
  5. wind: '微风'
  6. }
  7. render() {
  8. let { isHot, wind } = this.state
  9. return <h3 onClick={this.chang}>今天的天气很 {isHot ? "炎热" : "凉爽"},{wind}</h3>
  10. }
  11. chang = ()=>{
  12. this.setState({
  13. isHot: !this.state.isHot//这里的修改是一种合并,对比属性的变化,如果有赋新值,没有则跳过
  14. })
  15. }
  16. }
  17. ReactDOM.render(<Weather />, document.getElementById('test'))
  18. let a = new Weather()
  19. </script>

设置状态:setState

  1. setState(object nextState[, function callback])

不能在组件内部通过

  1. this.state
修改状态,因为该状态会在调用 setState() 后被替换。

  1. setState()
并不会立即改变 this.state,而是创建一个即将处理的
  1. state
  1. setState()
并不一定是同步的,为了提升性能
  1. React
会批量执行
  1. state
  1. DOM
渲染。

  1. setState()
总是会触发一次组件重绘,除非在
  1. shouldComponentUpdate()
中实现了一些条件渲染逻辑。

2.props

    1. React
    中组件通过 props 属性接收外部传入的数据,这点 Vue 跟 React 是一致的
  • react 中说的单向数据流值说的就是 props,根据这一特点它还有一个作用:

    1. 组件之间的通信
  • props 本身是

    1. 不可变的
    ,但是有一种情形它貌似可变,即是将
    1. 父组件的 state作为子组件的 props
    ,当父组件的 state 改变,子组件的 props 也跟着改变,其实它仍旧遵循了这一定律:
    1. props 是不可更改的
  1. <script type="text/babel">
  2. class MyComponent extends React.Component {
  3. render() {
  4. return (
  5. <ul>
  6. <li>{this.props.name}</li>
  7. <li>{this.props.age}</li>
  8. </ul>
  9. );
  10. }
  11. }
  12. ReactDOM.render(
  13. <MyComponent name="Bob" age="18" />,
  14. document.getElementById("test")
  15. );
  16. </script>

props的特点:

  1. 每个组件对象都会有props(properties的简写)属性

  2. 组件标签的所有属性都保存在props中

  3. 内部读取某个属性值:this.props.propertyName

  4. 作用:通过标签属性从组件外 向组件内传递数据(只读 read only)

  5. 对props中的属性值进行类型限制和必要性限制

对props进行限制

  1. 引入 prop-type 库,这就是专门用于限制 props 属性的一个库

  2. 导入 prop-type 库,到当前页面

  3. 根据 Person.propTypes = {} 进行限制

  1. class MyComponent extends React.Component {
  2. render() {
  3. return (
  4. <ul>
  5. <li>{this.props.name}</li>
  6. <li>{this.props.age}</li>
  7. </ul>
  8. );
  9. }
  10. }
  11. // 校验类型
  12. MyComponent.propTypes = {
  13. name: PropTypes.string, // 这里的 PropTypes 变量是全局挂载的
  14. age: PropTypes.number,
  15. };
  16. ReactDOM.render(
  17. <MyComponent name="Bob" age={18} />,
  18. document.getElementById("test")
  19. );

props的简写

  1. <script type="text/babel">
  2. class Weather extends React.Component {
  3. constructor(props) {//是否接受,取决于是否使用外部数据
  4. super(props)//只能上面接受了props,super()就去传递,否则后续的使用,可能就会出现问题
  5. }
  6. static propTypes = {
  7. name: PropTypes.string.isRequired,//限制name为字符串类型,必填
  8. // age: PropTypes.number,
  9. sex: PropTypes.string,
  10. speak: PropTypes.func
  11. }
  12. static defaultProps = {
  13. sex: '男',
  14. }
  15. render() {
  16. let { name, age, sex } = this.props
  17. return (
  18. <ul>
  19. <li>姓名:{name}</li>
  20. <li>性别:{sex}</li>
  21. <li>年龄:{age + 1}</li>
  22. </ul>
  23. )
  24. }
  25. }
  26. ReactDOM.render(<Weather name="tom" age={26} sex="女" />, document.getElementById('test'))
  27. </script>

函数组件使用props

  1. <script type="text/babel">
  2. // 函数组件
  3. function MyComponent(props) {
  4. return (
  5. <ul>
  6. <li>{props.name}</li>
  7. <li>{props.age}</li>
  8. </ul>
  9. );
  10. }
  11. // 校验类型
  12. MyComponent.propTypes = {
  13. name: PropTypes.string,
  14. age: PropTypes.number,
  15. };
  16. ReactDOM.render(
  17. <MyComponent name="Bob" age={18} />,document.getElementById("test")
  18. );
  19. </script>

3.ref

  1. React 中的 Refs 可以让我们访问 DOM 节点,它有三种使用方式:字符串方式,回调函数式,createRef。

  2. 在 React 中 Refs 提供了一种方式,允许用户访问DOM 节点或者在render方法中创建的React元素。

  3. 在 React单项数据流中,props是父子组件交互的唯一方式。要修改一个子组件,需要通过的新的props来重新渲染。

但是在某些情况下,需要在数据流之外强制修改子组件。被修改的子组件可能是一个React组件实例,也可能是一个DOM元素。对于这两种情况,React 都通过 Refs的使用提供了具体的解决方案。

回调函数方式

  1. <script type="text/babel">
  2. class MyComponent extends React.Component {
  3. handleAlert = () => {
  4. // 直接从组件实例上获取 myInput
  5. console.log(this.myInput); // <input type="text">
  6. alert(this.myInput.value);
  7. };
  8. render() {
  9. return (
  10. <div>
  11. {/* ref 直接定义成一个回调函数,参数就是节点本身,将它赋值给组件的一个 myInput 属性 */}
  12. <input ref={(ele) => (this.myInput = ele)} type="text" />
  13. <button onClick={this.handleAlert}>alert</button>
  14. </div>
  15. );
  16. }
  17. }
  18. ReactDOM.render(<MyComponent />, document.getElementById("test"));
  19. </script>

React官方提示:

如果 ref 回调函数是以内联函数的方式定义的,在更新过程中它会被执行两次,第一次传入参数 null,然后第二次会传入参数 DOM 元素。这是因为在每次渲染时会创建一个新的函数实例,所以 React 清空旧的 ref 并且设置新的。通过将 ref 的回调函数定义成 class 的绑定函数的方式可以避免上述问题,但是大多数情况下它是无关紧要的。

createRef -官方推荐使用

  1. <script type="text/babel">
  2. class MyComponent extends React.Component {
  3. // 创建 ref
  4. myInput = React.createRef();
  5. handleAlert = () => {
  6. console.log(this.myInput.current); // 这里需要注意,元素是在 current 属性上
  7. alert(this.myInput.current.value);
  8. };
  9. render() {
  10. return (
  11. <div>
  12. {/* 将创建好的 ref 附加到元素上 */}
  13. <input ref={this.myInput} type="text" />
  14. <button onClick={this.handleAlert}>alert</button>
  15. </div>
  16. );
  17. }
  18. }
  19. ReactDOM.render(<MyComponent />, document.getElementById("test"));
  20. </script>

上面就是使用 React.createRef() 方法创建 ref 的方式,特别需要注意的是,创建出来的 ref 的值是一个对象,我们需要的 DOM 元素是放在对象的 current 属性上,如上面的 this.myInput.current。

以上就是JavaScript中React面向组件编程怎么使用的详细内容,更多关于JavaScript中React面向组件编程怎么使用的资料请关注九品源码其它相关文章!