与href html标签混合react prop

时间:2018-12-05 14:11:46

标签: javascript reactjs

我是React.js和JavaScript的新手。我必须在href标签中传递两个电话号码-

phoneListHTML={[
                "<a href='tel:{phoneNumber}'>{phoneNumber}</a>".replace('{phoneNumber}', support.expPhone),
                "<a href='tel:{phoneNumber}'>{phoneNumber}</a>".replace('{phoneNumber}', support.expPhoneInternational),
                ]}

“超链接文本”没有被替换,而是实际的“超链接点击文本”被替换了。

2 个答案:

答案 0 :(得分:2)

使用正则表达式代替,该表达式允许使用g标志进行全局替换(所有出现)。

SO

phoneListHTML={[
      "<a href='tel:{phoneNumber}'>{phoneNumber}</a>".replace(/{phoneNumber}/g, support.expPhone),
      "<a href='tel:{phoneNumber}'>{phoneNumber}</a>".replace(/{phoneNumber}/g, support.expPhoneInternational),
                ]}

或者,您可以使用模板文字

phoneListHTML={[
      `<a href="tel:${support.expPhone}">${support.expPhone}</a>`),
      `<a href="tel:${support.expPhoneInternational}">${support.expPhoneInternational}</a>`),
                ]}

答案 1 :(得分:1)

理想情况下,您不应该像这样传递原始HTML。您应该向下传递包含数据的对象/数组,并允许您的组件基于该数据呈现HTML。

// Support information
const support = { phone: '123', international: '+44 123' };

// Render the App component
// passing in the support object as props
ReactDOM.render(
  <App support={support} />,
  document.getElementById('container')
);

// App accepts props and returns some JSX
// which contains the Support component
// with the support object passed to it in its props
function App(props) {
  return (
   <main>
     <h3>Support</h3>
     <Support support={props.support} />
   </main>
  )
}

// Returns JSX with the completed information
function Support({ support }) {
  const { phone, international } = support;
  return (
    <div>
      <a href={phone}>{phone}</a><br/>
      <a href={international}>{international}</a>
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>