reactjs - 使用 React defaultProps 正确设置 prop 的初始状态
问题描述
我的问题是关于焦点问题的: https ://www.testdome.com/d/react-js-interview-questions/304
我做到了这一点:
class Input extends React.PureComponent {
render() {
let {forwardedRef, ...otherProps} = this.props;
return <input {...otherProps} ref={forwardedRef} />;
}
}
const TextInput = React.forwardRef((props, ref) => {
return <Input {...props} forwardedRef={ref} />
});
class FocusableInput extends React.Component {
ref = React.createRef()
render() {
return <TextInput ref={this.ref} />;
}
// When the focused prop is changed from false to true,
// and the input is not focused, it should receive focus.
// If focused prop is true, the input should receive the focus.
// Implement your solution below:
componentDidUpdate(prevProps) {
if (prevProps.focused !== this.props.focused && !!this.props.focused)
{
if (this.ref.current !== document.activeElement)
{
this.ref.current.focus();
}
}
}
componentDidMount() {}
}
FocusableInput.defaultProps = {
focused: true
};
const App = (props) => <FocusableInput focused={props.focused} />;
document.body.innerHTML = "<div id='root'></div>";
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
我有:
The focused property has an initial state of true: Wrong answer
Changing the focused prop from false to true focuses the input: Correct answer
所以我得到了第二个测试正确但不是第一个,那个要求 props.focused 的初始状态为真。
查看我的代码,似乎我已经将其设置为 true?
解决方案
我不会在它下面签名,但这是该练习所期望的。如果focused
prop 是true
,则必须将输入集中在里面componentDidMount
。此外,如果focused
道具改变 - 焦点也必须改变。
class FocusableInput extends React.Component {
ref;
componentDidUpdate(prevProps) {
if (prevProps.focused !== this.props.focused) {
this.ref.focus();
}
}
componentDidMount() {
if (this.props.focused) {
this.ref.focus();
}
}
render() {
return <TextInput ref={(ref) => this.ref = ref} />;
}
}
推荐阅读
- oracle - 使用 Oracle 钱包配置 Quartz 调度程序
- typescript - 是否需要安装 NPM
- python - 将一个类初始化为另一个类时出现问题显示错误代码
- python - Python:从网页获取加载的资源(如 chrome 开发工具)
- codenameone - VKB 始终打开的表单
- python-3.x - 基于属性去重/组合对象
- python - 如何在不损失准确性的情况下将暗网权重转换为 CoreML 模型?
- python - 当数据集大小不是批量大小的倍数时,Keras 会发生什么?
- excel - 在 Excel 中的工作表函数之间传递 VBA 类的实例
- reactjs - 我在反应钩子项目中的 POST 请求上有 400 个代码