React几种传递参数的方法

1.父组件向子组件传参

回调函数也是参数的一种,也可以传给子组件,达到子组件控制父组件的目的

import React from 'react';
import ReactDOM from 'react-dom';

function Son(props) {
	return 
父组件的名称是{props.name}
} function Father(props) { return ( ); } ReactDOM.render(, document.getElementById('root'));

React几种传递参数的方法_第1张图片

2.事件处理函数传参

import React from 'react';
import ReactDOM from 'react-dom';

function Father(props) {
	function getName(e) {
		console.log(`传递参数的值是${e}`);
	}
	return ();
}
ReactDOM.render(, document.getElementById('root'));

3.路由传参

函数组件,可以使用hook

import React from 'react';
import ReactDOM from 'react-dom';



import {
	BrowserRouter as Router,
	Switch,
	Route,
	Link,
	useParams
} from "react-router-dom";


export default function ParamsExample() {
	return (
		
      
  • Yahoo321
  • Yahoo123
} />
); } function Child(props) { let { id } = useParams(); return (

ID: {id}

); } ReactDOM.render(, document.getElementById('root'));

React几种传递参数的方法_第2张图片

类组件,使用this.props.match.params

import React from 'react';
import ReactDOM from 'react-dom';



import {
	BrowserRouter as Router,
	Switch,
	Route,
	Link,
	useParams
} from "react-router-dom";


export default function ParamsExample() {
	return (
		
      
  • Yahoo321
  • Yahoo123
); } // } /> // // function Child(props) { // let { // id // } = useParams(); // return ( //
//

ID: {id}

//
// ); // } class Child extends React.Component { constructor(props) { super(props); } componentDidMount() { //console.log(this.props.match); // console.log(this.props.history); //console.log(this.props.location); } render() { return (

ID:{this.props.match.params.id}

) } } ReactDOM.render(, document.getElementById('root'));

React几种传递参数的方法_第3张图片

注意,引入子组件需要这么写:

4.URL传参

import React from 'react';
import ReactDOM from 'react-dom';



import {
	BrowserRouter as Router,
	Switch,
	Route,
	Link,
	useParams
} from "react-router-dom";


export default function ParamsExample() {
	return (
		
      
  • Yahoo321
  • Yahoo123
); } // } /> // // function Child(props) { // let { // id // } = useParams(); // return ( //
//

ID: {id}

//
// ); // } class Child extends React.Component { constructor(props) { super(props); } componentDidMount() { //console.log(this.props.match); // console.log(this.props.history); console.log(this.props.location.search); } render() { return (

ID:{this.props.match.params.id}

) } } ReactDOM.render(, document.getElementById('root'));

5. history.push传递参数

function onTouch(e) {
	history.push({
		pathname: "/home",
		state: {
			postId: e
		}
	});

}
import {useLocation} from 'react-router-dom';
let location = useLocation();
console.log("id", location.state.postId)

 

你可能感兴趣的:(前端,react)