React 实现动态添加元素到列表

这篇博客适合React初学者,介绍了如何实现动态添加元素到列表的功能。通过学习,你可以理解React的状态(state)和属性(props),掌握父子组件间的数据传递,复习ES6语法,并了解组件设计的基本思路。
摘要由CSDN通过智能技术生成

首先声明一下,大佬请绕道,以下内容为React纯基础,适合小白新手练习Demo,后面会持续更新

做成的效果如下图

知识点梳理:
1 理解React state
2 理解React props
3 掌握父子间的值传递
4 了解ES6语法
5 主要要理解思路,分清组件之间的关系,大概思路在代码中有相关注释(虽然没人会看)
在这里插入图片描述
直接上代码示例:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';

//父组件
class App extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            todos: ['Java', 'Php', 'React']
        }
    }


//如果子类想改变父类组件的属性,只能通过父类声明函数供子组件调用来实现
   addTodo = (todo) => {
       const {todos} = this.state
       todos.unshift(todo)
       this.setState({todos})

   }

    render() {
        const { todos } = this.state
 
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React中,可以使用Refs来获取子元素的高度,然后将其传递给父组件,从而动态设置父元素的高度。具体实现步骤如下: 1. 在子组件中,使用Refs获取子元素的高度。可以使用React.createRef()来创建Refs对象,然后在子元素的渲染函数中将Refs绑定到子元素的DOM节点上。 ```javascript class ChildComponent extends React.Component { constructor(props) { super(props); this.childRef = React.createRef(); } render() { return ( <div ref={this.childRef}> // 子元素内容 </div> ); } } ``` 2. 在子组件中,使用componentDidMount()方法,将子元素的高度传递给父组件。这个方法会在子元素挂载完成后自动调用。 ```javascript class ChildComponent extends React.Component { componentDidMount() { const height = this.childRef.current.offsetHeight; this.props.onHeightChange(height); } render() { return ( <div ref={this.childRef}> // 子元素内容 </div> ); } } ``` 3. 在父组件中,定义一个状态变量来保存子元素的高度,然后将这个状态变量传递给子组件。 ```javascript class ParentComponent extends React.Component { constructor(props) { super(props); this.state = { height: 0 }; this.handleHeightChange = this.handleHeightChange.bind(this); } handleHeightChange(height) { this.setState({ height: height }); } render() { return ( <div style={{ height: this.state.height }}> <ChildComponent onHeightChange={this.handleHeightChange} /> </div> ); } } ``` 在这个例子中,父元素的高度会根据子元素的高度来动态设置。当子元素的高度发生变化时,子组件会将的高度传递给父组件,父组件会重渲染并设置自己的高度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值