【问题标题】:ReactJS : How to wrap knockoutJS page inside React componentReactJS:如何将 knockoutJS 页面包装在 React 组件中
【发布时间】:2019-06-01 14:10:33
【问题描述】:

查看 (HTML)

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2><span data-bind="text: fullName"> </span>!</h2>

nameConcat.js (KnockoutJS)

var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);

    this.fullName = ko.pureComputed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);
};

ko.applyBindings(new ViewModel("Tom", "Haykens"));

反应组件

class NameConcat extends React.Component {
  render() {
    return (
       ???
    );
  }
} 

我是 ReactJS 新手。如何从 ReactJS 组件显示 knockoutJS 应用程序页面?在 ReactJS 中重写 KnockoutJS 页面不是一种选择。

提前致谢。

【问题讨论】:

    标签: javascript reactjs knockout.js single-page-application


    【解决方案1】:

    在我的项目中,骨架​​是在 Durandel 中设计的,部分原因是我无法在 React 中使用重写选项。

    所以这是我必须使用的:

    案例 1) - 想要以 KO 方式绑定数据

    public observableVariable = Observable();
    
    public binding() { // durandle lifecycle hook // observable declared with the class 
        reactDom.render(<span data-bind={`text: observableVariable `}></span>, document.getElementById('reactRoot'));
        }
    

    案例 2) - 想要将已经 KO 的页面绑定到 React 并让 DOM 在真实 DOM 中更新。

    public observableVariable = Observable();
    
    public binding() { // durandle lifecycle hook // observable declared with the class 
        reactDom.render(<div data-bind={`compose: { model: '-- index page where the knockout binding is written --',activationData: { --Observable parameter--: --Observable data--}    }`}></div>, document.getElementById('reactRoot'));
        }
    

    案例 3) - 模板绑定

    // 在顶部声明所有可观察对象

    // 所有这些组件都可以从 react 组合子组件发送到任何地方

    <div dangerouslySetInnerHTML={{
                __html: `<!--ko widget: {
                            kind: '--index--',
                            name: 'sample comp',
    // write all the observable dependencies here , 
                            id: 'sample Id'
                        } -->
                        <!-- /ko -->`}} />
    

    案例 4)如果您想使用 observable 加载常规反应组件:我的意思是,如果您希望在 observable 中维护一些数据以用于反应。

    拥有一个跟踪对象并使用 Observable subscribe 保持数据同步:

    {
        self reactPropValue;
        self.selectedVals.subscribe(function (newValue: any) {
                        let val = ko.toJSON(newValue);
                        reactPropValue= ko.toJSON(selectedVals());
                    });
    }
    

    现在你可以将它作为一个 prop 传递给 react 组件,并且每次可观察到的更改时,订阅都会确保获得一个新值,不要忘记将你的 reactDom 包装在一个函数中并调用订阅,因为设计它不会触发重新加载。

    如果你不在 durandel,你可能需要自己添加 ko.applybinding 否则没问题。

    如果您收到任何错误消息,请注意控制台窗口中的错误消息,可能有一些。

    对不起,如果我的回答格式不正确。

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 2018-10-14
      相关资源
      最近更新 更多