gpt4 book ai didi

javascript - 如何让 React 监听在 Jquery 中调用的点击事件

转载 作者:行者123 更新时间:2023-11-29 22:59:00 25 4
gpt4 key购买 nike

我正在使用 dabeng/OrgChart在 react 应用程序中。当用户单击节点时,Jquery 会填充一个输入框。可以看到一个例子here .

我想用 React 而不是 Jquery 来做这件事,这样我就可以将选定的节点保存在状态中,而不是保存值的输入框。

我已经尝试过使用引用之类的方法,试图看看我是否可以在 jquery 函数中调用 react 方法,但没有任何乐趣。

也许是 publisher/subscriber model将是解决方案,但不确定如何实现类似的东西。

class OrgTreeBase extends Component {
state = {
list: {
'name': 'Ball game',
'children': [
{
'name': 'Football',
'children': [
{
'name': 'man united',
'children': [
{ 'name': 'fred' },
{ 'name': 'ander herrera' },
{ 'name': 'scott mctominay' },
]
}
]
},
{
'name': 'Basketball',
'children': [
{'name': 'lakers'},
{ 'name': 'warriors' },

]
},
{ 'name': 'Volleyball' }
]
},
currentLevel: 0,
currentItem: [],
selectedItem: '',
};

componentDidMount() {
this.$el = $(this.el);
let datasource = this.state.list;

this.getId = () => {
return (new Date().getTime()) * 1000 + Math.floor(Math.random() * 1001);
}

//creates the initial chart with the following settings
var oc = $('#chart-container').orgchart({
'data': datasource,
'chartClass': 'edit-state',
'exportButton': true,
'exportFilename': this.state.name,
'parentNodeSymbol': 'fa-th-large',
'createNode': function ($node, data) {
$node[0].id = this.getId;
},
})

//when node is selected
oc.$chartContainer.on('click', '.node', function () {
var $this = $(this);
console.log("this is : " + $this.find('.title').text());
$('#selected-node').val($this.find('.title').text()).data('node', $this);
});

...

onNodeSelected = (node) => {
console.log(node + " was selected");
}

我希望在单击节点时调用 this.onNodeSelected()。

    onNodeSelected = (node) => {
console.log(node + " was selected");
}

提前感谢您在这方面给我的任何帮助。

最佳答案

IMO 您已经 promise 将 jQuery 与此库一起使用。所以我不明白为什么你不能做这样的事情让我们说:

    //somewhere above
const self = this;

//when node is selected
oc.$chartContainer.on('click', '.node', function () {
var $this = $(this);
console.log("this is : " + $this.find('.title').text());
$('#selected-node').val($this.find('.title').text()).data('node', $this);

//set state and save node here on click. Or the node's text value
self.setState({})
});

既然这不在您的要求之内,我应该说我建议这样做的原因是因为 DOM 似乎是由 orgChart 库生成的,并且很难向其添加 react 监听器。没有任何理由不能在 jQuery 点击函数中调用 react setState。

如果不添加 jQuery 和 React 都是相当大的库,做的事情基本相似的警告,我就提出这个建议也是错误的。你可能已经知道了,但是,我仍然想建议你找一个不同的组织库或者用 React 创建你自己的组织库。

关于javascript - 如何让 React 监听在 Jquery 中调用的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56012775/

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