java render()_如何从类render方法中提取JSX?

我认为解析返回的元素是错误的方法 . 一个挑战是 style 的值将是一个对象( styles.container ===样式键/值的散列),而您需要一个可以映射到对象的键 .

我认为最可重用的方法是利用React上下文(我假设RN支持!)来构建一个 styleName ,它可以在你下载组件树时进行扩充 .

这是一个初始方法,它做了一些假设(例如,每个组件都将 styleName 作为prop提供;您可能希望在设计时而不是运行时提供它) . 简而言之,您使用此HOC包装要参与的每个组件,并将 styleName 作为每个组件的prop . 连接这些 styleName 值以生成映射到样式的上下文化名称 .

这个例子产生:

Some Text

const CascadingStyle = (styles, Wrapped) => class extends React.Component {

static displayName = 'CascadingStyle';

static contextTypes = {

styleName: React.PropTypes.string

}

static childContextTypes = {

styleName: React.PropTypes.string

}

// pass the current styleName down the component tree

// to other instances of CascadingStyle

getChildContext () {

return {

styleName: this.getStyleName()

};

}

// generate the current style name by either using the

// value from context, joining the context value with

// the current value, or using the current value (in

// that order).

getStyleName () {

const {styleName: contextStyleName} = this.context;

const {styleName: propsStyleName} = this.props;

let styleName = contextStyleName;

if (propsStyleName && contextStyleName) {

styleName = `${contextStyleName}_${propsStyleName}`;

} else if (propsStyleName) {

styleName = propsStyleName;

}

return styleName;

}

// if the component has styleName, find that style object and merge it with other run-time styles

getStyle () {

if (this.props.styleName) {

return Object.assign({}, styles[this.getStyleName()], this.props.styles);

}

return this.props.styles;

}

render () {

return (

);

}

};

const myStyles = {

container: {backgroundColor: 'green', color: 'red'},

container_text: {color: 'blue'}

};

const Container = CascadingStyle(myStyles, (props) => {

return (

);

});

const Text = CascadingStyle(myStyles, (props) => {

return (

);

});

const Component = () => {

return (

Some Text

);

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值