【发布时间】:2018-09-28 05:47:39
【问题描述】:
import React from "react";
import { render } from "react-dom";
import { createStore, applyMiddleware } from "redux";
import { Provider, connect } from "react-redux";
import thunk from "redux-thunk";
const disabled = (state = true, action) => {
return action.type === "TOGGLE" ? !state : state;
};
class Button extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.disabled !== this.props.disabled && !this.props.disabled) {
// this.ref.focus(); // uncomment this to see the desired effect
}
}
render() {
const { props } = this;
console.log("rendering", props.value);
return (
<div>
<input
type="checkbox"
onClick={() => {
props.toggle();
this.ref.focus(); // doesn't work
}}
/>
<input
disabled={props.disabled}
ref={ref => {
this.ref = ref;
}}
/>
</div>
);
}
}
const toggle = () => ({
type: "TOGGLE"
});
const A = connect(state => ({ disabled: state }), { toggle })(Button);
const App = () => (
<Provider store={createStore(disabled, applyMiddleware(thunk))}>
<A />
</Provider>
);
render(<App />, document.getElementById("root"));
当复选框被选中时,我想关注input。
但是,this.ref.focus() 必须在组件使用 props.disabled === false 重新渲染后才能调用,因为带有 disabled 属性的 input 无法聚焦。
如果我执行componentDidUpdate 中的逻辑,我就能实现我想要的。但这不是一个干净的解决方案,因为逻辑特定于 onClick 处理程序而不是生命周期事件。
还有其他方法可以做到这一点吗? (最好有一个有效的代码框示例)
【问题讨论】:
-
IMO,在
componentDidUpdate中更新是正确的方式,因为重新渲染和焦点都是组件的状态和行为,您无法将它们完全解耦。我什至会说您应该将切换状态移动到组件中,并为onToggle和onClick提供一些回调道具。 -
@Avery235 是什么让你说“这不是一个干净的解决方案,因为逻辑特定于 onClick 处理程序而不是生命周期事件”?
标签: javascript reactjs redux redux-thunk