首页 > 解决方案 > 如何在 React 中的功能组件之间传递数据?

问题描述

在 React 中,我们可以通过以下方式使用状态和道具在基于类的组件之间传递数据:

应用程序.js

import Name from './Name';
import React, { Component } from 'react'


export class App extends Component {
  state = {
    name: "Tarun"
  }

  render() {
    return (
      <Name name={this.state.name}/>        
    )
  }
}

export default App

名称.js

import React, { Component } from 'react'

export class Name extends Component {
    render() {
        return (
            <div>
                My name is : {this.props.name}
            </div>
        )
    }
}

export default Name

App.js但是现在既然 React 已经引入了函数式组件,那么如果我对和都使用函数式组件,那么等效的代码是什么Name.js

标签: javascriptreactjs

解决方案


使用钩子你可以写这样的东西。

App

import React, { useState } from 'react'

export default function App() {

  // `useState` returns an array with the state
  // and the method used to update the state
  // You can initialise the state with a variable/object
  const [name, setName] = useState('Tarun');

  // No need for a render method
  // Just return the JSX from the function
  return <Name name={name} />;
}

Name

import React from 'react'

// Props are passed down like normal function args
// Destructure `names` from the props object
export default function Name({ name }) {
  return <div>My name is: {name}</div>;
}

推荐阅读