替换电子邮件模板中的标签

时间:2017-08-30 22:41:43

标签: reactjs redux

我试图找出替换组件中标签的最佳方法。所以,给出以下文字......

-synctex 0

和此:

*|FIRSTNAME|*,

*|LINK|*

You can sign in with your email address (*|EMAIL|*)
Your password is:
*|PASSWORD|*

Thanks!

*|SIGNATURE|*

我希望在用户输入时更新的实时预览窗口中显示:

export default class Template extends Component {
  componentWillMount () {
    this.setState({
      mergeTags: {
        '*|FIRSTNAME|*': 'John',
        '*|LINK|*': 'www.test.com',
        '*|EMAIL|*': 'email@email.com',
        '*|PASSWORD|*': 'supersecurepassword',
        '*|SIGNATURE|*': 'Bob Law's Law Blog'
      }
    })
  }

1 个答案:

答案 0 :(得分:1)

不知道您的确切设置,但是,或类似的东西,应该工作。 JSFiddle演示https://jsfiddle.net/jonahe/zrrfyxh7/

class Parent extends React.Component {
    constructor(props) {
    super(props);
    this.state = { 
        '*|FIRSTNAME|*': 'John',
      '*|LINK|*': 'www.test.com',
      '*|EMAIL|*': 'email@email.com',
      '*|PASSWORD|*': 'supersecurepassword',
      '*|SIGNATURE|*': "Bob Law's Law Blog"
    };
  }
  // use componentDidMount, or else the ref thing below won't work.
  componentDidMount() {
    let innerText = this.templateElement.innerHTML;
    // loop through all the properties / "tags"
    for(let tagKey in this.state) {
        // replace the occurence of the tag key string, with the tag value in this.state
        innerText = innerText.replace(tagKey, this.state[tagKey])
    }
    this.templateElement.innerHTML = innerText;

  }
  render() {
    // get a reference to the element that contains the raw template
    return <p ref={ template => this.templateElement = template }>
      *|FIRSTNAME|*,
      *|LINK|*

      You can sign in with your email address (*|EMAIL|*)
      Your password is:
      *|PASSWORD|*

      Thanks!

      *|SIGNATURE|*
    </p>;
  }
}

希望有所帮助。如果有什么不清楚的话告诉我。

编辑:添加了更多类似React的示例,其中模板不是纯文本,而是HTML。 JSFiddle https://jsfiddle.net/jonahe/539g38kc/