gpt4 book ai didi

javascript - 有没有办法遍历 React 构建的树?

转载 作者:数据小太阳 更新时间:2023-10-29 04:21:30 24 4
gpt4 key购买 nike

我需要为 HTML 页面构建一个可视化编辑器。 ReactJS 似乎是一个不错的选择。目前我面临以下问题:

我对我的数据建模:

var Model = {
title: 'Hello',
description: 'Pellentesque eleifend urna ac purus tempus...',
date: new Date().toString()
};

并构建了将其数据存储在上述结构中的组件:

var App = React.createClass({
getInitialState: function () {
return {
value: Model
}
},
handleMouseEnter: function (event) {
$(event.target).css('outline', '1px solid red').attr('contenteditable', true);
},
handleMouseLeave: function (event) {
var t = $(event.target), v = this.state.value;
t.css('outline', 'none').attr('contenteditable', false);
v[t.attr('property')] = t.text();
this.setState({value: v});
},
render: function () {
var v = this.state.value;
return (
<div>
<pre style={{whiteSpace: 'normal'}}>{JSON.stringify(this.state)}</pre>
<h1 onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} property="title">{v.title}</h1>
<p onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} property="description">{v.description}</p>
<p onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} property="date">{v.date}</p>
</div>
);
}
});

React.renderComponent(<App />, document.getElementById('app'));

在那种特殊情况下它有效。但我想摆脱 onMouseEnteronMouseLeave 属性,只保留 property 字段。像那样:

<pre style={{whiteSpace: 'normal'}}>{JSON.stringify(this.state)}</pre>
<h1 property="title">{v.title}</h1>
<p property="description">{v.description}</p>
<p property="date">{v.date}</p>

我考虑过创建 mixin。然后,在 componentDidMount 事件中,将处理程序附加到具有 property 属性的所有元素。但我找不到实现这一目标的方法。

我的问题是:有没有办法遍历 React 构建的树?我注意到 React 开发人员工具(Chrome 扩展)可以做到这一点。

类似问题:React.js component creating parent child relations and iterating

最佳答案

所以你想要:

<h1 onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} property="title">{v.title}</h1>

作为

<h1 property="title">{v.title}</h1>

我会为此使用另一个 Component,它负责渲染特定类型的组件,例如 redux-form

实现您想要做的事情的最简单方法如下:

class MyField extends Component {
constructor(props) {
super(props);
this.handleMouseEnter = this.handleMouseEnter.bind(this);
}
handleMouseEnter() { ... }
render() {
const { property, children } = this.props;
if (property === 'title') {
return (
<h1 onMouseEnter...>{children}</h1>
);
}
}
}

然后你可以在任何其他组件上这样调用它:

<MyField property="title">Stackoverflow</MyField>

一种更专业但也更困难的方法是 Field 的 redux 形式实现, 他们甚至在上面使用 React.createElement生成 HTML(我在上面的例子中用 if-else 做了什么)。

如果您需要在它之外访问它的任何数据,您可以通过属性将其传递给它一个函数,或者将 MyField 组件连接到 redux(redux-form 也这样做)。

我还会通过 props 传递您想要应用于 MyField 组件的任何特定的一次性样式。

关于javascript - 有没有办法遍历 React 构建的树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26531864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com