如何使用 onClick 将状态/道具发送到 React 中的另一个组件?
props和state是 React 的主要概念。实际上,只有 props 和/或 state 的变化会触发 React 重新渲染你的组件并可能更新浏览器中的 DOM
Props :它允许您将数据从父组件传递到子组件。
State :虽然 props 允许您将数据从父组件传递到子组件,但状态用于更改组件,嗯,从内部更改状态。对状态的更改也会触发 UI 更新。
使用 onClick 事件将 state/props 发送到另一个组件:首先我们将 state/props 存储到父组件中,即在哪个组件中触发 onClick 事件。然后要将状态传递给另一个组件,我们只需将其作为道具传递。为了更好地理解看这个例子。
对于基于类的组件。
应用程序.js :
Javascript
// First Component i.e. App import React, { Component } from 'react'; import './App.css' import Component2 from './Component2'; class App extends Component { state={data:""} changeState = () => { this.setState({data:`state/props of parent component is send by onClick event to another component`}); }; render(){ return (
Compnent1
Javascript
import React from 'react'; const Component2 = (props) => { return (
Compnent2
{props.data}
Javascript
// First component i.e App import React, { useState } from 'react'; import './App.css' import Component2 from './Component2'; function App() { const [state, setstate] = useState({data:""}) const changeState = () => { setstate({data:`state/props of parent component is send by onClick event to another component`}); }; return (
Compnent1
Javascript
// Second Component import React from 'react'; import './Component2.css' export default function Component2(props) { return (
Compnent2
{props.data}
组件2.js:
Javascript
import React from 'react'; const Component2 = (props) => { return (
Compnent2
{props.data}
对于基于函数的组件。
应用程序.js:
Javascript
// First component i.e App import React, { useState } from 'react'; import './App.css' import Component2 from './Component2'; function App() { const [state, setstate] = useState({data:""}) const changeState = () => { setstate({data:`state/props of parent component is send by onClick event to another component`}); }; return (
Compnent1
组件2.js:
Javascript
// Second Component import React from 'react'; import './Component2.css' export default function Component2(props) { return (
Compnent2
{props.data}
输出 :
在点击按钮之前:
点击按钮后: