【问题标题】:Interpolating variables into a string将变量插入字符串
【发布时间】:2017-03-18 14:56:43
【问题描述】:

虽然我是一位经验丰富的程序员,但我对 js 和反应完全陌生。

我正在尝试在我自己的组件中使用react-native-svg 组件Path。这个例子很清楚,但它使用字符串文字作为坐标。例如:

<Path d="M 10 20 L 30 40" stroke="red" />

但是,我想使用来自组件道具 x1、y2、x2、y2 的坐标而不是文字,但我不知道如何将它们与各种以M 和L 为示例的字符。

【问题讨论】:

标签: javascript react-native string-interpolation


【解决方案1】:

如果您使用 ES2015 功能,template strings 将是一种可能的方法,例如:

<Path
    d={`M ${this.props.x1} ${this.props.y1} L ${this.props.x2} ${this.props.y2}`}
    stroke="red"
/>

注意反引号而不是引号。

【讨论】:

  • 这行得通,谢谢。有没有办法查看上面代码构建的完整路径标记?类似于在浏览器中查看网页的源代码。
  • 您可以像使用其他表达式一样使用模板字符串,它们的计算结果为字符串。即:const path = `...`; console.log(path); return &lt;Path d={path} ... /&gt;
【解决方案2】:

这看起来像我的question。您可以传入一个项目数组并将它们连接起来以创建您的字符串。

<Path d={['M', x1, y1, 'L', x2, y2].join(' ')} stroke="red" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多