一、父传子
- //父组件
- import './App.css';
- import React, { useState } from 'react';
- import Chil from './zizujian'
- function App() {
- return (
- <div className="App">
- <Chil onMessage={handleMessage} text='我是父组件传的值'></Chil>
- </div>
- );
- }
-
- export default App;
-
-
- //子组件
- import React from 'react';
- import { Component } from 'react'
- export default class A extends Component {
- render() {
- return (
- <div>
- {this.props.text}
- </div>
- )
- }
- }
-
二、子向父
父组件
- //父组件
- import React, { useState } from 'react';
- import Chil from './zizujian'
- import { Link } from 'react-router-dom';
- function App() {
- const [message, setMessage] = useState('');
- const handleClick = (msg) => {
- console.log('----',msg)
- setMessage(msg);
- };
- return (
- <div className="App">
- <p>信息来自子组件: {message}</p>
- //此处的handleCli须和子组件传值过来的函数名一致
- <Chil handleCli={handleClick} text='我是父组件船的zhi'></Chil>
- <Link to='/aa'>跳转页面</Link>
- </div>
- );
- }
-
- export default App;
-
-
- //子组件
- import React from 'react';
- import { Component } from 'react'
- export default class A extends Component {
- render() {
- return (
- <div>
- //父组件的传值
- {this.props.text}
-
- <button onClick={this.handleClick.bind(this)}>传递信息给父组件</button>
- </div>
- )
- }
- handleClick () {
- //此处的方法名必须和父组件的一致
- this.props.handleCli('我是子组件发过来的')
- };
- }
-
本次博客只记录了props方式传值,react还有兄弟间传值,跨级传值,还未记录,学习之路任重道远,前端学无止境啊