react-3(父子组件传值,引入样式,实现双向数据绑定)

本文介绍了在React中如何进行父子组件之间的数据传递,包括不建议的父组件修改子组件state的方式和子组件修改父组件state的正确做法。此外,还探讨了在jsx中添加样式的方法,如行内样式、外部样式引入以及模块化css的配置和使用。最后,文章讲解了React中的双向数据绑定,展示了一个简单的输入框与state同步变化的例子。
摘要由CSDN通过智能技术生成

父子组件更改数据

父组件修改子组件state(不建议):        

        父组件获取到子组件的实例(通过refs--(已被弃用)),通过子组件的setSate()来更改子组件state

父组件

<Child ref="child"></Child>

this.refs.child.setState({msg:'hello'})

子组件改父组件state:

        父组件传递修改自己的setState函数给子组件调用

父组件文件

//父组件

import React, { Component } from 'react'
import Child from './2-Child'
class PC extends Component {
    constructor(props) {
        super(props);
        this.state = {
            parentMSg: 'parentMSg'
        }

    }
    
    //传递的修改自己state的函数
    changeParentState = () => {
        this.setState({ parentMSg: 'hello' })
    }

    render() {
        return (
            <div>
                <Child parentMSg={this.state.parentMSg} changeParentState={this.changeParentState}></Child>
            </div>
        )
    }
}
export default PC

子组件文件

//子组件

import React, { Component } from 'react'
class Child extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>
                <p>父组件数据:{this.props.parentMSg}</p>
                //调用父组件的setState函数
                <button onClick={this.props.changeParentState}>更改父组件数据</button>
            </div>
        )
    }
}
export default Child

在jsx中添加样式

行内样式

        使用双花括号,第一个花括号代表变量,第二个花括号代表对象

<div style={
  {cplor:'red'}}></div>
const btnStyle={
                width:100,
     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值