let a = <components data={1}/>
能否通过操作a 改变 data 的值
import { useState } from 'react'
const Component = ({ data }: { data: number }) => {
return <div>{data}</div>
}
let a = <Component data={1} />
export default function App() {
const [, rerender] = useState({})
return (
<div className="App">
{a}
<button
onClick={() => {
const next = JSON.parse(JSON.stringify(a))
//$$typeof为Symbol,type为函数JSON无法复制需要手动赋值
//注意React只会在开发模式下对对象进行冻结,如果是生产模式
//可以不用复制a直接将其props赋值为一个新的props
next['$$typeof'] = (a as any)['$$typeof']
next.type = a.type
++next.props.data
a = next
rerender({})
}}
>
increment
</button>
</div>
)
}
4 回答1.7k 阅读
2 回答1.1k 阅读✓ 已解决
1 回答1k 阅读✓ 已解决
2 回答2.6k 阅读
4 回答1.3k 阅读
1 回答725 阅读✓ 已解决
2 回答896 阅读✓ 已解决
React.cloneElement(element, { data })