反应:从类转换为具有状态的功能组件
Posted
技术标签:
【中文标题】反应:从类转换为具有状态的功能组件【英文标题】:react: Convert from Class to functional component with state 【发布时间】:2021-02-21 20:47:59 【问题描述】:如何将类组件转换为函数式组件?
import React, Component from 'react'
class Test extends Component
state =
value: "test text",
isInEditMode: false
changeEditMode = () =>
this.setState(
isInEditMode: this.state.isInEditMode
);
;
updateComponentValue = () =>
this.setState(
isInEditMode: false,
value: this.refs.theThexInput.value
)
renderEditView = () =>
return (
<div>
<input type="text" defaultValue=this.state.value ref="theThexInput" />
<button onClick=this.changeEditMode>X</button>
<button onClick=this.updateComponentValue>OK</button>
</div>
);
;
renderDefaultView = () =>
return (
<div onDoubleClick=this.changeEditMode
this.state.value>
</div>
;
render()
return this.state.isInEditMode ?
this.renderEditView() :
this.renderDefaultView()
export default Test;
我假设需要使用钩子和破坏,但不知道如何实现它。 有没有好的指导方针或最佳实践可以遵循?
【问题讨论】:
这个step-by-step guide 不错,但我建议您首先阅读并使用钩子构建功能组件,而不是仅仅尝试遵循指南。如果您已经熟悉功能组件而不是类组件,那么该指南应该会有所帮助。 有很多关于这个主题的指南、教程和官方文档。请先尝试自己尝试,如果遇到困难,请在此处回复。 【参考方案1】:我简要解释了发生了什么:
const Test = () =>
// Use state to store value of text input.
const [value, setValue] = React.useState("test text" /* initial value */);
// Use state to store whether component is in edit mode or not.
const [editMode, setEditMode] = React.useState(false /* initial value */);
// Create function to handle toggling edit mode.
// useCallback will only generate a new function when setEditMode changes
const toggleEditMode = React.useCallback(() =>
// toggle value using setEditMode (provided by useState)
setEditMode(currentValue => !currentValue);
, [
setEditMode
] /* <- dependency array - determines when function recreated */);
// Create function to handle change of textbox value.
// useCallback will only generate a new function when setValue changes
const updateValue = React.useCallback(
e =>
// set new value using setValue (provided by useState)
setValue(e.target.value);
,
[setValue] /* <- dependency array - determines when function recreated */
);
// NOTE: All hooks must run all the time a hook cannot come after an early return condition.
// i.e. In this component all hooks must be before the editMode if condition.
// This is because hooks rely on the order of execution to work and if you are removing
// and adding hooks in subsequent renders (which react can't track fully) then you will
// get warnings / errors.
// Do edit mode render
if (editMode)
return (
// I changed the component to controlled can be left as uncontrolled if prefered.
<input
type="text"
autoFocus
value=value
onChange=updateValue
onBlur=toggleEditMode
/>
);
// Do non-edit mode render.
return <div onDoubleClick=toggleEditMode>value</div>;
;
这是runnable example
【讨论】:
以上是关于反应:从类转换为具有状态的功能组件的主要内容,如果未能解决你的问题,请参考以下文章