繁体   English   中英

混合反应prop与href html标签

[英]Mix react prop with href html tag

我是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),
                ]}

“超链接文本”未被替换,但实际的“超链接点击文本”被替换。

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

所以

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>`),
                ]}

理想情况下,您不应该像这样传递原始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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM