父组件中传递值给子组件可以通过props来实现。在父组件中,将要传递给子组件的值作为props的属性传递给子组件。在子组件中,通过props来接收父组件传递的值。

修改后的代码如下:

父组件:

import { createRoot } from 'react-dom/client'
import Test from './Test'

const root = createRoot(document.getElementById('root'))
root.render(<Test name='aaa'/>)

子组件:

import { useState } from 'react'
import './style/index.scss'

const Test = (props) => {
	const [count, change] = useState(1)
	const data = [1, 2, 3, 4, 5]
	const handleClick = item => {
		console.log(item.target.innerHTML)
	}
	return (
		<div>
			<h1 className="yuanshen">HELLO,REACT</h1>
			<a
				href="https://www.baidu.com"
				onClick={e => e.preventDefault()}>
				点击按钮
			</a>
			<br />
			<img
				className="imgLogo"
				src={require('./logo.png')}
				alt="原神"
			/>
			{data.map(item => (
				<p
					className="item"
					key={item}
					onClick={handleClick}>
					{item}
				</p>
			))}
			<hr />
			<div>数字:{count}</div>
			<div>父组件传递的值:{props.name}</div> // 接收父组件传递的值
			<button onClick={() => change(count + 1)}>点击++</button>
			<br />
		</div>
	)
}

export default Test

在子组件中,通过props.name来接收父组件传递的值,并在页面上展示

react父组件import createRoot from react-domclientimport Test from Testconst root = createRootdocumentgetElementByIdrootrootrenderTest name=aaa子组件import useState from reactimport styleindexscssconst T

原文地址: https://www.cveoy.top/t/topic/iuUJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录