2 回答

TA貢獻1982條經驗 獲得超2個贊
只是想確保,您想要的是:當用戶Enter在文本字段上鍵入時按下時,按鈕將顯示加載視覺效果,對嗎?我認為您不必將 ref 傳遞給按鈕組件,您可以將狀態傳遞isLoadingShown到您的WaitingButton
等待按鈕.js
return (
<div className={classes.buttonWrapper}>
<Button
ref={this.props.innerRef}
disabled={loading || disabled}
onClick={this.handleClick}
{...other}>
<React.Fragment>
{children}
{this.props.isLoadingShown && this.buildLoader(loading, classes)}
</React.Fragment>
</Button>
</div>
);
然后在表單組件中
state = {
isLoadingShown: false,
}
triggerClick() {
this.setState({ isLoadingShown: true })
}
render(){
...
<Paper>
<TextField
style={{marginBottom: '8px'}}
label="A textbox!"
fullWidth
onKeyPress={(e) => { if (e.key === "Enter") this.triggerClick(); }} />
<WaitingButton
variant="contained"
color="primary"
isLoadingShown={this.state.isLoadingShown}
onClick={(e) => {
console.log('Button clicked :)', e.target);
}}>
Press enter in textbox!
</WaitingButton>
</Paper>
...
}
不要忘記isLoadingShown再次設置為falsecomponentWillUnmount

TA貢獻1818條經驗 獲得超11個贊
我只是試圖重現你的情況。我為它創建了一個代碼沙盒。我想我發現了問題??雌饋?React.forwardRef 只適用于 prop name forwardedRef 所以嘗試在你的代碼中將 innerRef 屬性重命名為 forwardedRef 。
const withInnerRef = React.forwardRef((props, ref) => <WaitingButton
forwardedRef={ref} {...props}
/>);
還有你的 render() 函數
<Button
ref={this.props.forwardedRef}
disabled={loading || disabled}
onClick={this.handleClick}
...
你可以用我的簡化代碼和盒子試試https://codesandbox.io/s/intelligent-cori-rb5ce
添加回答
舉報