首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何重新设计功能组件?

如何重新设计功能组件?
EN

Stack Overflow用户
提问于 2020-05-09 12:26:26
回答 2查看 195关注 0票数 1

在这里,我将一个click事件绑定到子组件上,以使父组件重新呈现。根据正式的解决方案,函数组件中没有使用forUpdate()方法的方法,但折衷方案是使用setState重新呈现。但是,当单击父组件时,不会重命名。在函数组件中,子组件使用什么方法来重新划分父组件?

以下是子组件代码:

代码语言:javascript
复制
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>
    )
}

以下是父组件代码:

代码语言:javascript
复制
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()方法相同。你怎么做到的?非常感谢!

EN

回答 2

Stack Overflow用户

发布于 2020-05-09 13:19:27

问题是,onClick事件在<RefreshContent onClick={ refresh }>上不会触发,因为onClick是DOM事件,但是RefreshContent只是一个react组件,因此对于RefreshContentonClick将作为React传递。

您应该做的是在RefreshContent中将onClick附加到原生DOM元素。

,例如

将事件附加到DOM元素

代码语言:javascript
复制
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

票数 2
EN

Stack Overflow用户

发布于 2020-05-11 05:15:24

@m5khan谢谢你的回答!RefreshContent被打包成样式-组件,可以触发单击事件,并且状态也会通过单击改变!

代码语言:javascript
复制
const RefreshContent = styled.div`
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 0;
    text-align: center
`
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61696691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档