"instantiate"同类新元素做出反应



让我们考虑一下这个鼠标事件:

function onMouseUp(e) {
e.preventDefault();
if (isText) {
mouseSelRect.current.style.left = x1 + 'px';
mouseSelRect.current.style.top = x2 + 'px';
mouseSelRect.current.style.width = x3 + 'px';
mouseSelRect.current.style.height = x4 + 'px';
createTextArea(x1, x2, x3, x4);
}
}

我想创建多个";实例";就文本区域而言,每次我制作一个选择矩形并释放鼠标时,随着选择矩形的创建,我可以自定义新文本区域的尺寸。然而,网络开发的主要问题是,环境严重鼓励人们成为;在呈现页面之前声明所需的所有元素";尽可能。

我想知道是否有可能从事件中创建一个不一定在钩子返回部分的新元素。

createTextArea函数可以返回一个组件,您可以将该组件添加到组件列表(例如,一个状态(

const List = () => {
const [componentList, setComponentList] = React.useState([])
const onMouseUp = (e) => {
e.preventDefault();
if (isText) {
mouseSelRect.current.style.left = x1 + 'px';
mouseSelRect.current.style.top = x2 + 'px';
mouseSelRect.current.style.width = x3 + 'px';
mouseSelRect.current.style.height = x4 + 'px';
const component = createTextArea(x1, x2, x3, x4);
setComponentList([...componentList, component])
}
}
return (
<div>{componentList.map(Component => <Component />)}</div>
)
}

我不知道你想对组件列表做什么,但在上面的例子中,我只是渲染了它。但你可以使用数组来做任何你想做的事情。

创建新元素并触发页面的重新呈现以包含这些元素是绝对可能的。这就是该框架的目的:动态页面内容响应状态的变化。(检查https://www.w3schools.com/react/react_intro.asp或其他地方的介绍材料,将证明它。(

最新更新