2016-05-12 82 views
1

我想创建一个简单的Wizard组件。我不知道如何绑定handleChange函数onChange输入事件以及如何进入传递的上下文(这是我的自定义类在某处定义并在ParentClass中实例化)。React模板中的绑定函数

Uncaught SyntaxError: Unexpected token }

这里是我的Wizard组件和简单的模板,我创建的测试:

export class ParentClass extends React.Component { 
    render() { 
     let template = `<input value=${context.testVal} onChange=${context.handleChange.bind(context, event)}>`; // how to invoke this code inside Wizard using TestContext class??? 
     let testContext = new TestContext(); 

     return (
      <Wizard template={template} context={testContext} /> 
     ); 
    } 
} 

export class TestContext { 
    testVal = null; 

    constructor() { 
     this.testVal = 10; 
    } 

    handleChange(e) { 
     console.log(e); 
    } 
} 

export class Wizard extends React.Component { 
    context: null; 

    constructor(props) { 
     super(props); 

     this.context = this.props.context; 
    } 

    render() { 
     return (
      <div dangerouslySetInnerHTML={{__html: this.props.template}}> 
      </div> 
     ); 
    } 
} 

我用ES2015Babel编译。

[编辑]

我修改了代码和问题。我现在看到你们的意思是说“删除$”。

你不理解我。我想声明HTML代码与一些变量绑定(作为一个字符串)+一些上下文类应该包含所有声明模板的逻辑。当我有这些时,我想将它们作为参数传递到Wizard,并使用该模板替换此WizardHTML(同时执行JSX)。换一种说法。我想在Wizard组件中使用动态模板的通用机制。

+1

只要删除'' - 在这个意义上不需要模板 - 只需传入'' – Chris

+1

@Chris是对的,显然你也必须删除'$'标志。 –

+0

请看看我编辑的问题。 – Nickon

回答

1

你可能要好好工作 JSX在这里。这里是如何做到这一点了一个例子:

function Template (props) { 
    // Though there's no `event` variable that should be getting bound here and 
    // you'd be better off binding `handleChange` to the instance in 
    // TestContext's constructor. 
    return <input 
    value={props.context.testVal} 
    onChange={props.context.handleChange.bind(props.context, event)} 
    />; 
} 

export class ParentClass extends React.Component { 
    render() { 
     let testContext = new TestContext(); 

     // You could instead create the element here using Template and pass 
     // that in. You could even pass it as a child of <Wizard> and just 
     // have Wizard render its children. 
     return (
      <Wizard template={Template} context={testContext} /> 
     ); 
    } 
} 

// ... 

export class Wizard extends React.Component { 
    // ... 
    render() { 
     return (
      <div> 
       <this.props.template context={this.props.context} /> 
      </div> 
     ); 
    } 
} 

你可以做一些您实际要求这样,但它不会工作,你希望的方式 - 你不能渲染函数对象转换为一个HTML字符串(所以我刚刚删除了onChange部分)。

export class ParentClass extends React.Component { 
    render() { 
     let template = (context) => `<input value=${context.testVal} />`; 
     let testContext = new TestContext(); 

     return (
      <Wizard template={template} context={testContext} /> 
     ); 
    } 
} 

// ... 

export class Wizard extends React.Component { 
    // ... 
    render() { 
     return (
      <div dangerouslySetInnerHTML={{__html: this.props.template(this.context)}} /> 
     ); 
    } 
} 

但是,真的,只要使用JSX就可以实现您想要的更好。