React How to dynamically change the html tag

For example, there is such a demand, sub-assemblies passed over by the parent component props, to dynamically display <h1>the <h6>label, may be the first matter react, think about vuehow to achieve it?

Vue implementation

Parent component

<template>
	<div>
		<Son :tagSize="1"/>
	</div>
</template>

<script>
import Son from '../components/Son';
export default {
    name: "Father",
    components:{
        Son
    }
};
</script>

Subassembly

<template>
	<div>
        <h1 v-if="tagSize === 1">测试</h1>
        <h2 v-else-if="tagSize === 2">测试</h2>
        <h3 v-else-if="tagSize === 3">测试</h3>
        <h4 v-else-if="tagSize === 4">测试</h4>
        <h5 v-else-if="tagSize === 5">测试</h5>
        <h6 v-else>测试</h6>
	</div>
</template>

<script>
export default {
	name: "Son",
	props: {
		tagSize: {
            type:Number,
            default:1
        }
	}
};
</script>

With vuetemplate syntax that we can also achieve the above requirements, but can not because the dynamic htmllabel it is not very flexible, lower imagine, if you can modify the label, the label directly by way of stitching, for example "<h"+tagSize+">测试</h"+tagSize+">"the way, in such a way to deal with this demand, then obviously very convenient, ado, take a look at reactimplementation.

React implementation

Parent component

import React from 'react';
import Child from './Child.js';

class Father extends React.Component{
    render(){
        return (
            <React.Fragment>
                <Child size = { 1 }/>
            </React.Fragment>
        )
    }
}
export default Father;

Subassembly

import React from 'react';

const Child = (props)=>{
    let MarkUp = `h${props.size}`;
    return (
        <React.Fragment>
            <MarkUp>你好</MarkUp>
        </React.Fragment>
    )
}

export default Child;

Compared'll find two ways reactto achieve this kind of demand would be more appropriate, reactsyntax of JSXgrammar, syntax personal feeling than vuethe templatetemplate syntax is more flexible, but Vuenow also has support JSX.

Published 29 original articles · won praise 0 · Views 263

Guess you like

Origin blog.csdn.net/weixin_39782183/article/details/104751431