在这里,我将一个click事件绑定到子组件上,以使父组件重新呈现。根据正式的解决方案,函数组件中没有使用forUpdate()方法的方法,但折衷方案是使用setState重新呈现。但是,当单击父组件时,不会重命名。在函数组件中,子组件使用什么方法来重新划分父组件?
以下是子组件代码:
export default function Refresh({ refresh }: Props) {
return (
<RefreshContainer>
<RefreshContent onClick={ refresh }>
<RefreshIcon color={ '#4F7DAF' } className={ 'icon-refresh' } size={ '16px' } marginRight={ '4px' }/>
<RefreshSpan color={ '#4F7DAF' } text={ '点击刷新' } marginRight={ '4px' } />
<RefreshSpan color={ '#999999' } text={ '换一批内容' } />
</RefreshContent>
</RefreshContainer>
)
}以下是父组件代码:
export default () => {
const [ refresh, setRefresh ] = useState<boolean>(false)
const update = useCallback(() => {
// test
document.querySelector('.found-scroll-container')!.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
})
setRefresh(refresh => !refresh)
}, [])
return (
<div className={ 'found-scroll-container' }>
<div className={ 'found-scroll-content' }>
<div className={ 'container-padding' }>
<Carousel type={ '2' }/>
<Type />
</div>
<div className={ 'recommend-container-padding' }>
<Recommend quantity={ '6' }/>
<RecommendNewMusic />
<HotWindVane />
<Radio/>
</div>
<Refresh refresh={ update } />
</div>
</div>
)
}单击RefreshContainer后,让父组件重发,效果应该与window.reload()方法相同。你怎么做到的?非常感谢!
发布于 2020-05-09 13:19:27
问题是,onClick事件在<RefreshContent onClick={ refresh }>上不会触发,因为onClick是DOM事件,但是RefreshContent只是一个react组件,因此对于RefreshContent,onClick将作为React传递。
您应该做的是在RefreshContent中将onClick附加到原生DOM元素。
,例如
将事件附加到DOM元素
const RefreshContent = props => (
<div onClick={props.onClick}>{props.children}</div>
);这将导致触发onClick事件,并且更新父组件中的状态。
https://codesandbox.io/s/infallible-roentgen-7nczb?file=/src/components/Refresh.jsx:606-696
发布于 2020-05-11 05:15:24
@m5khan谢谢你的回答!RefreshContent被打包成样式-组件,可以触发单击事件,并且状态也会通过单击改变!
const RefreshContent = styled.div`
display: flex;
justify-content: center;
align-items: center;
font-size: 0;
text-align: center
`https://stackoverflow.com/questions/61696691
复制相似问题