具有部分提供的属性的JSX元素文字

时间:2016-06-13 15:17:36

标签: javascript reactjs

使用React.cloneElement可以为部分填充(缺少更好的单词)元素提供其他属性。一个人为的例子是:

function createPopulatedElement(el, v) {
    return React.cloneElement(el, {value: v});
}

const ImportantContent = React.createClass({
    render: function() {
       return (
          <strong> {this.props.value} </strong>
       );
    }
});

let populatedElement = createPopulatedElement(<ImportantContent/>, 'foo');

ReactDOM.render(populatedElement , $('#app2')[0]);

现在,上面代码中的<ImportantContent/>将(?)评估为:

<strong>{this.props.value}</strong>

......我希望能够做到:

let populatedElement= createPopulatedElement(
    (<span>{this.props.value} </span>),
    'foo');

...无需在上面的例子中声明一个包装器React类(ImportantContent)。但是上面的代码失败了:

Uncaught TypeError: Cannot read property 'value' of undefined

......哪种有道理。有没有办法为某个函数或ReactJS组件提供部分填充(缺少更好的单词)元素(然后将添加其他属性)作为JSX元素文字,而无需创建类?

(上面的代码是SSCCE,我知道单独的createPopulatedElement函数没有意义,因为我可以在实例化value={'foo'}组件时直接传递ImportantContent。 )

更新

ctrlplusb建议使用无状态功能组件。这确实比一个类略好:

let F = (props)=>(<span>{props.value} </span>);
let populatedElement= createPopulatedElement(
              <F/>
          , 'foo');
ReactDOM.render(populatedElement, $('#app3')[0]);

...但仍然引入了新类型(F)。直接使用匿名箭头函数使其更加紧凑,并避免引入单独的类型失败解析:

let populatedElement= createPopulatedElement(
         <(props)=>(
                <span>{props.value} </span>
                   )
         />
     , 'foo');

1 个答案:

答案 0 :(得分:2)

你几乎就在那里 - 当你创建一个无状态组件并一次性使用它时,你需要在React.createElement中手动包装它而不是使用JSX:

let populatedElement= createPopulatedElement(
  React.createElement(props => <span>{props.value}</span>),
  'foo'
);