react中同级组件如何传值


本文摘自PHP中文网,作者藏色散人,侵删。

react中同级组件传值的方法:首先打开相应的前端文件;然后设置共同的父组件传值;接着创建一个子组件,并将数据传递到父组件中;最后使父组件接收值,并传入另一个子组件中即可。

本教程操作环境:Windows7系统、react17.0.1版本,该方法适用于所有品牌电脑。

推荐:《react视频教程》

React同级组件传值

bbdf598b2b7d98df375c1613d3583b8.png

在React中同级组件本身是没有任何关联的,要想有联系只能通过共同的父组件传值,一个子组件将数据传递到父组件中,父组件接收值再传入另一个子组件中

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Hello 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="box"></div>

<script type="text/babel">

//子组件向父组件传值,父组件接收再传递给另一个子组件

class Childone extends React.Component{

constructor(props){

super(props);

this.state={color:"lightblue"}

}

handlecolor(){

this.props.fn("red");            

//在触发方法中通过props添加一个新的fn方法,并且将颜色参数red传入父组件

this.setState({color:"red"});

}

render(){

return(

<div>

<h4 style={{color:this.state.color}}>我是第一个子组件</h4>

<button onClick={this.handlecolor.bind(this)}>改变第二个子组件颜色</button>      

//给第一个子组件绑定一个方法,点击就触发,注意要绑定this

</div>

)

}

}

class Childtwo extends React.Component{

constructor(props){

super(props);

}

render(props){

return(

<h4 style={{color:this.props.co}}>我是第二个子组件</h4>              

//利用prop属性从外界即父组件获取参数,不能用state,state是内部使用的

)

}

}

class Parents extends React.Component{

constructor(props){

super(props);

this.state={childtwocolor:"lightblue"};

}

change(color) {

this.setState({childtwocolor: color});

}

render(props) {

return (

<div>

<Childone fn={(color)=>{this.change(color)}}></Childone>        

//第一个子组件的方法fn,将参数red传入函数change中,更新父组件本身的颜色childtwocolor

<Childtwo co={this.state.childtwocolor}></Childtwo>                  

//第二个子组件获取父组件本身的颜色,当父组件颜色更新时,它也会随之更新

</div>

)

}

}

ReactDOM.render(

<Parents />,

document.getElementById('box')

);

</script>

</body>

</html>

以上就是react中同级组件如何传值的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

怎么解决webstrom写React代码报错问题

怎么用React

不用脚手架搭建React的方法

React中如何引入样式

一些关于React的常见面试题(分享)

React怎么跳出新页面

angular与angularjs、React和vue的简单对比

React fabric是什么

React设置文件路径别名的具体方法你知道么

React中如何引入插件

更多相关阅读请进入《React》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...