This is the first article I participated in beginners’ introduction.


Difficulty *

Learn how to create the React Native component.

demand

Leave to check the loan status

React Native uses nested components to highlight a word in a text.

	<Text>
		<Text style={{textDecorationLine:'underline'}} >leave</Text></Text>Copy the code

This is what I might call hard coding, which is not only a hassle to write, but also makes the code look messy in real business.

write

So we’re going to write a component instead. Before WRITING a component, I think about how I’m going to use it.

// My ideal use would be like this
<LighText 
	keys={['leave']} 
	lighStyle={{textDecorationLine:'underline'}}> Leave to check the borrowing status </LighText>Copy the code

This component is implemented by separating a paragraph of text by keyword, creating them with highlighting and default states respectively.


The idea behind this code is to recursively look for a keyword in a string, split it up when it is found, and add the first, second and last words to the array, so that the keyword will always have an even index, and the default text will always have an odd index. Then repeat the process until the keyword is not found. Here is the implementation code:

/* * Wrap the important part of a paragraph with a separate text tag *@return [] array even for highlighting content */
const markKeys = (title, keys) = > {
        const split = (arr, keys) = > {
            // Receive a string
            arr.forEach(item= > {
                let arrs, key
                for (let index = 0; index < keys.length; index++) {
                    const word = keys[index]
                    if (item.indexOf(word) > -1) {
                        arrs = item.split(word)
                        key = word
                        break}}if(! arrs) {return false
                }
                // Duplicate strings are generated when there are multiple keywords
                let index = result.indexOf(item)
                if (index > -1) {
                    result.splice(index, 1)}/ / to keep
                result.push(arrs[0])
                result.push(key)
                result.push(arrs[1])
                split(arrs, keys)
            })
        }
        let arr = [title] // The received string
        let result = []
        split(arr, keys)
        return result
    }
Copy the code

I wanted to write the code of the component, but I found that it was very wordy after Posting it, so I left it to you on the screen

conclusion

Review the past and learn the new. After writing this article, I found many problems. This code is functional, but it’s basically a zero. This code will be optimized in my NTH article, and the optimization process and ideas will be posted.