I need to clarify myself some terminologies that i found too ambigous, or useless to apply in daily programming, some of them is: UI, Component, Behaviour, View, Model.
I could describe a Component
as:
Component = function(behavior, view)
What does behavior
mean ?
behavior = function(props) -> model
Yes, a behavior
is a function, which receives props
as input, and return a model
A model
in this case is just any data structure.
What does a view
mean ?
view = function(model) -> UI
A view
is a function which receives a model
and returns a UI
.
UI
means User Interface, is what a user could see, feel and interact with.
Example:
Let's make a Counter
component with React and Hooks !
This is the makeComponent
, which receives a behavior
, a view
and returns a Component
import React from 'react'
const Component = ({behavior, view, ...rest}) => {
const props = behavior(rest)
const View = view
return <View {...props} />
}
const makeComponent = (behavior, view) => {
return (props) => <Component {...props} behaviour={behaviour} view={view} />
}
export default makeComponent
The Counter
behavior:
import {useState, useCallback} from 'react'
const behavior = ({initialCount}) => {
const [count, setCount] = useState(initialCount)
const increment = useCallback(() => setCount(count + 1))
const decrement = useCallback(() => setCount(count - 1))
return {initialCount, count, increment, decrement}
}
The Counter
view:
const view = ({initialCount, count, increment, decrement}) => {
return (
<div>
<button onClick={increment}>+</button>
<div>Current count: {count}</div>
<button onClick={decrement}>-</button>
</div>
)
}
Finally, let's make a Counter
component:
const Counter = makeComponent(behavior, view)
React.render(<Counter initialCount={0} />, body)
Voilla, i got a clean React component !
But, is this MVC
?
Yes ! The behavior
is exactly what does a controller
mean.
So, is a Component
the same as MVC
?
No ! Component
has only two arguments: The V and the C, there's no M.
Top comments (1)
Thanks Truong~
Great insight on
MVC
as Iused
to consider React to be just a view library.