2016-05-12 85 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就可以實現您想要的更好。