Answer a question

In Angular we can create a custom pipe to change data format. For example, see the UpperCasePipe:

{{ value_expression | uppercase }}

There doesn't appear to be pipes in React, so my question is: How can we use pipes in React?

Answers

There are simply no pipes, because anything evaluated in the brackets is considered plain JavaScript. Because this is evaluated as plain javascript, there is simply no need for pipes. If this.state.variable is a string, I can use the .toUpperCase() prototype to display the string in all uppercase:

{this.state.variable.toUpperCase()}

This would be functionally equivalent to UpperCasePipe:

{{variable | uppercase}}

It's easy enough to just create a wrapper function, and use that. For example, if you wanted to create a custom function to uppercase just the first letter, we can use this function from here:

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

We then would call it like so:

{capitalizeFirstLetter(this.state.variable)}
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐