我有一个组件,在某些情况下,我想给它一个value和一个onChange属性,特别是当一个id属性被传递给这个组件时。
<TextField
hintText="Recipe Name"
ref={r => this.recipeName = r}
{this.props.id ? 'value={this.state.name}' : ''}
{this.props.id ? 'onChange={this.handleNameChange}' : ''} />然而,当我使用这段代码时,我得到了这个错误。
BabelLoaderError: SyntaxError: Unexpected token (71:13)
69 | hintText="Recipe Name"
70 | ref={r => this.recipeName = r}
> 71 | {this.props.id ? 'value={this.state.name}' : ''}
| ^
72 | {this.props.id ? 'onChange={this.handleNameChange}' : ''} />我知道只要把视图逻辑放在组件之外就行了,就像这样:
{ this.props.id ?
<TextField
hintText="Recipe Name"
ref={r => this.recipeName = r}
value={this.state.name}
onChange={this.handleNameChange}/> :
<TextField
hintText="Recipe Name"
ref={r => this.recipeName = r} />
}但是因为我使用了多个<TextField />组件,所以这段代码变得非常笨拙。有没有什么方法可以让我在组件属性内部而不是外部使用? :视图逻辑?
发布于 2016-08-28 03:03:58
你可以像下面这样尝试一下。
<TextField
hintText="Recipe Name"
ref={r => this.recipeName = r}
value = {this.props.id ? this.state.name : undefined} // no need to use curly braces inside another curly brace
onChange = {this.props.id ? this.handleNameChange : undefined}
/>发布于 2016-08-28 04:06:55
通过修改Ahmmed的代码,我发现通过将三元运算符的else条件设置为undefined,就好像从未设置正确的值value和onChange一样。这段代码不会抛出任何错误,并且省去了我大量的输入:
<TextField
hintText="Recipe Name"
ref={r => this.recipeName = r}
value = {this.props.id ? this.state.name : undefined}
onChange = {this.props.id ? this.handleNameChange : undefined} />https://stackoverflow.com/questions/39184641
复制相似问题